3/**
 * 表单设计器
 */
mini.parse();

var mainField = document.querySelector('#mainField');//主面板

var cFormName = mini.get("cFormName");//表单名
// var formTypes = mini.get("formTypes");//模式(表单/档案)
var cLayoutType = mini.get("cLayoutType");//布局方式（表格布局/自有布局）
var cLayoutPhone1=mini.get("cLayoutPhone1");//布局手机
var treeData = mini.get("treeData");//字段列表

var cTableField = mini.get("cTableField");//英文
var cTableField_ch = mini.get("cTableField_ch");//原标题
// var cField = mini.get("cField");//英文
var cLadText = mini.get("cLadText");//中文
var cTabText = mini.get("cTabText");//页签名formDesignData
var cFormTitle = mini.get("cFormTitle");//文本内容
var cComType = mini.get("cComType");//组件类型
var cAdapterPhone=mini.get("cAdapterPhone");//适配手机
var cFontSize = mini.get("cFontSize");//文本字号
var cLength = mini.get("cLength");//长度
var cFormat = mini.get("cFormat");//日期格式
var cDateDefault = mini.get("cDateDefault");//是否默认当前日期
var cReference = mini.get("cReference");//参照
// var cBgReference = mini.get("cBgReference");//参照2
var cCombo = mini.get("cCombo");//下拉框内容
var cCheckbox = mini.get("cCheckbox");//复选框内容
var cGridType = mini.get("cGridType");//表格列类型
var cGroup = mini.get("cGroup");//表格列分组
var cMath = mini.get("cMath");//公式
var cRequire = mini.get("cRequire");//验证
var cNull = mini.get("cNull");//是否必填
var cSpinner = mini.get("cSpinner");//保留小数位数
var cTree = mini.get("cTree");//档案模式的关键字段
var cCannotbezero=mini.get("cCannotbezero");//不能为零
var addBtn=mini.get("addBtn");//获取增加按钮
var disable=mini.get("disable");//获取禁用

var textbox_index = 0;
var tab_index = 0;
var table_index = 0;
var checkbox_index = 0;
var combobox_index = 0;
var buttonedit_index = 0;
var datepicker_index = 0;
var textarea_index = 0;
var fileupload_index = 0;
var formname_index = 0;
var spinner_index = 0;

var textbox_editIndex = [];
var tab_editIndex = [];
var table_editIndex = [];
var checkbox_editIndex = [];
var combobox_editIndex = [];
var buttonedit_editIndex = [];
var datepicker_editIndex = [];
var textarea_editIndex = [];
var fileupload_editIndex = [];
var formname_editIndex = [];
var spinner_editIndex = [];

var click_type = '';
var click_types = [];
var click_id = '';
var click_ids = [];
var pre_click_type = '';
var pre_click_id = '';

var modularId;//菜单id（数字）
var parId;
var modular;//菜单id（完整）
var buttons = "1,2,3,4,5";//按钮ids
var openId = '';//新增保存/编辑保存flag
var ref = {};//参照数据

var tabsId_arr = [];
var tab_index = 1;

var rightClickCol = {}; //表格右键点击选中的列对象
var gridClick_id;
var properties = [];
var grid_message;

var action;
var edit_data;
var formListId;
var formName;
var designMode = 'form';//设计模式
var cTreeData = '';//档案数据
var cTreeStruct = '';//档案树结构

var editFlag = false;//是否为编辑刚进入页面时
var lockFlag = true;//遮罩

cRequire.setData([
    {

    },
    {
        'id':'none','text':'无'
    },{
        'id':'email','text':'必须是邮箱地址'
    },{
        'id':'url','text':'必须是URL'
    },{
        'id':'int','text':'必须是整数(int)'
    },{
        'id':'float','text':'必须是数字(float)'
    },{
        'id':'english','text':'必须输入英文'
    }
]);
disable.setData([
    {

    },
    {
        'id':'false','text':'否'
    },{
        'id':'true','text':'是'
    }
]);
cNull.setData([
    {

    },
    {
        'id':'false','text':'否'
    },{
        'id':'true','text':'是'
    }
]);
cComType.setData([
    {

    },
    {
        'id':'textbox','text':'文本框'
    }, {
        'id':'textarea','text':'文本域'
    }, {
        'id':'datepicker','text':'时间选择器'
    }, {
        'id':'spinner','text':'数值'
    }, {
        'id':'buttonedit','text':'参照'
    }, {
        'id':'combobox','text':'下拉框'
    }
]);
cAdapterPhone.setData([
    {

    },
    {
        'id':'false','text':'否'
    },{
        'id':'true','text':'是'
    }
]);
cCannotbezero.setData([
    {

    },
    {
        'id':'false','text':'确认不可为零'
    },{
        'id':'true','text':'可以为零'
    }
]);
cFontSize.setData([
    {

    },
    {
        'id':'12','text':'12'
    },{
        'id':'13','text':'13'
    },{
        'id':'14','text':'14'
    },{
        'id':'15','text':'15'
    },{
        'id':'16','text':'16'
    },{
        'id':'17','text':'17'
    },{
        'id':'18','text':'18'
    },{
        'id':'19','text':'19'
    },{
        'id':'20','text':'20'
    },{
        'id':'21','text':'21'
    },{
        'id':'22','text':'22'
    },{
        'id':'23','text':'23'
    },{
        'id':'24','text':'24'
    }
]);
// formTypes.setData([
//     {
//         'id':'form','text':'表单'
//     },{
//         'id':'file','text':'列表档案'
//     },{
//         'id':'complex','text':'树形档案'
//     },{
//         'id':'treeFile','text':'单个树形档案'
//     }
//
// ]);
cLayoutType.setData([
    {

    },
    {
        'id':'layout_free','text':'自由布局'
    },{
        'id':'layout_table','text':'表格布局'
    }
]);
mini.get("cLayoutPhone1").setData([
    {

    },
    {
        "id":"layout_false","text":"否"

    },{
        "id":"layout_true","text":"是"
    }
]);
// cTree.setData([
//     {
//         'id':false,'text':'否'
//     },{
//         'id':true,'text':'是'
//     }
// ]);

var modelId = localStorage.getItem("modelId");
var formDesignData = {};

$(function () {
    $.when(initDataReq()).done(function (data) {
        if (data.state == 'success'){
            formDesignData.jumpType = 'model';
        } else{
            formDesignData.jumpType = 'model_edit';
            formDesignData.edit_data = data.formItem;
            formDesignData.formListId = data.formListId;
            formDesignData.formName = data.formName;
            formDesignData.modelId = data.modelId;
        }
        init();
    })
})

function  initDataReq() {
    var defer = $.Deferred();
    $.ajax({
        url : ajaxUrl + "/formltems/findByModelId.do?modelId=" + modelId,
        type : 'post',
        dataType : 'json',
        contentType : 'application/json',
        success : function (data) {
            defer.resolve(data);
        },
        error : function (data) {

        }
    });
    return defer.promise();
}

function init(enable) {
    $.ajax({
        url: ajaxUrl + "/formList/finByModelId.do",
        type: "POST",
        data: {
            modelId:modelId
        },
        success: function (data) {
            console.log(data, 'inner编辑的数据');
            if(data.message=="获取数据成功"){
                addBtn.disable();
                mini.get("setButtonBtn").disable();
                mini.get("setMenuBtn").disable();
                mini.get("saveBtn").disable();


                var form2 = new mini.Form("#mainField")
                var form = new mini.Form("#form1")
                // var treeData=mini.get("treeData");
                // var rect=mini.get("thisId");
                form.setEnabled(false);
                form2.setEnabled(false);
                // var center=mini.get("center");
                // center.setEnabled(false);
                $("center").attr("disabled",true);


            }
        },
        error: function (data) {
        }
    });





    var menuJump = parent.isMenuJump();//是否是菜单跳转（add）
    if(menuJump) {//菜单跳转（新增）
        action = 'add';
        edit_data = [];
        formListId = '';
        formName = '';

    }else if(formDesignData != null) {//建模跳转（新增）
        if(formDesignData.jumpType == 'model') {
            action = 'add';
            edit_data = [];
            formListId = '';
            formName = '';

            //modelId = formDesignData.id;
        }else if (formDesignData.jumpType == 'model_edit') {
            action = 'edit';
            edit_data = formDesignData.edit_data;//编辑的数据
            formListId = formDesignData.formListId;
            formName = formDesignData.formName;
            //modelId = formDesignData.modelId;
        }
    }else {//按钮跳转（新增/编辑）
        var formDesignAction = localStorage.getItem("formDesignAction");
        formDesignAction = $.parseJSON(formDesignAction)[0];
        console.log(formDesignAction,'formDesignAction');
        action = formDesignAction.action;//add/edit
        edit_data = formDesignAction.edit_data;//编辑的数据
        formListId = formDesignAction.formListId;
        formName = formDesignAction.formName;
        modelId = formDesignAction.modelId;
    }

    // 加载字段
    $.ajax({
        url: ajaxUrl + "/tableClass/findByModelId.do?modelId="+modelId,
//        url: "http://localhost:8080/DSMP/tableClass/findByModelId.do?modelId=38",
        type: "post",
        dataType: "json",
        traditional: true,
        success: function(data){
            var arr_leftTree1 = data.data;
            console.log(arr_leftTree1);
            for(var i=0;i<arr_leftTree1.length;i++) {
                arr_leftTree1[i].field = arr_leftTree1[i].tableClassName;
                arr_leftTree1[i].fieldCh = arr_leftTree1[i].tableChClassName;
                arr_leftTree1[i].id = arr_leftTree1[i].tableClassName;
                arr_leftTree1[i].name = arr_leftTree1[i].tableClassName;
                arr_leftTree1[i].text = arr_leftTree1[i].tableChClassName;
                arr_leftTree1[i].name_ch = arr_leftTree1[i].tableChClassName;
                arr_leftTree1[i].isTableName = true;//是否是表名
                if(arr_leftTree1[i].mTableId == 0) {//主表
                    arr_leftTree1[i].ptype = "main";
                } else {
                    arr_leftTree1[i].ptype = "child";
                }
                var defaultArr = {
                    ptype: 'default',
                    children: []
                };
                if(arr_leftTree1[i].children != []) {

                    var child = arr_leftTree1[i].children;
                    console.log("child.length:" + child.length);
                    for(var j=0;j<child.length;j++) {
                        child[j].id = child[j].field;
                        child[j].name = child[j].field;
                        child[j].text = child[j].fieldCh;
                        child[j].name_ch = child[j].fieldCh;
                        child[j].isTableName = false;//是否是表名
                        if(arr_leftTree1[i].mTableId == 0) {//主表
                            child[j].ptype = "main";
                        } else {
                            child[j].ptype = "child";
                        }
                        if(child[j].state == '1'){//默认字段
                            defaultArr.children.push(child[j]);
                            // delete child[j];
                        }

                    }
                    var newArr = [];
                    for(var m=0;m<child.length;m++) {
                        if(m != null) {
                            newArr.push(child[m]);
                        }
                    }
                    newArr.push();
                    var len = arr_leftTree1[i].children.length;
                    // arr_leftTree1[i].children[len] = defaultArr;

                }
            }
            treeData.setData(arr_leftTree1);
            var arr_leftTree2 = treeData.getList();
            console.log(arr_leftTree2);

            if(action == 'edit') {

            }else {
                mask();
                mini.get("autoLayoutBtn").disable();
                mini.get("setButtonBtn").disable();
                mini.get("setMenuBtn").disable();
                mini.get("saveBtn").disable();
                lockFlag = true;
            }

            if(enable == 'enable') {
                unmask();
                mini.get("autoLayoutBtn").enable();
                mini.get("setButtonBtn").enable();
                mini.get("setMenuBtn").enable();
                mini.get("saveBtn").enable();
                lockFlag = false;
            }

            //拖拽树节点
            treeData.on("nodemousedown",function(e) {
                console.log(e);
                // if(e.record.pid != 0) {

                if(!e.record.isTableName && e.record.ptype == "main") {//主表子节点
                    $(".mini-tree-nodeshow").attr("draggable","true");
                    setCompOption(e.record.type);
                    var type = create_type(e.record.type);
                    onMenuDrag(type,e.record);
                }else if(e.record.isTableName && e.record.ptype == "child"){//子表根节点
                    $(".mini-tree-nodeshow").attr("draggable","true");
                    onMenuDrag('table',e.record);
                }

                // }
            })

            //绑定需要拖拽改变大小的元素对象
            bindResize(document.getElementById('mainField'));

            // var minH = $( "#form-outlookbar" ).height() - 5;
            // $( "#mainField" ).resizable({
            //     minHeight: minH,
            //     //maxHeight: 250,
            //     //maxWidth: 350,
            //     //minWidth: 200
            //     //resize: function () {
            //     //	var h = $("#mainField").height()-$(window).height();
            //     //    $("#mainField").scrollTop(h);
            //     //}
            // });

            if(action == 'edit') {

                properties = edit_data;
                console.log(properties,'编辑');
                for(var m=0;m<properties.length;m++) {
                    if(properties[m].ref != undefined) {
                        properties[m].ref = $.parseJSON(properties[m].ref);
                    }
                }
                onDesignModeChanged({value: edit_data[0].formTypes});
                var edit_treeData = $.parseJSON(edit_data[0].cDataTree);
                console.log(edit_treeData,'edit_treeData');
                for(var p=0;p<arr_leftTree1.length;p++) {
                    for(var j=0;j<edit_treeData.length;j++) {
                        if(arr_leftTree1[p].tableClassName == edit_treeData[j].tableClassName) {
                          edit_treeData[j]=   arr_leftTree1[p];
                        }
                    }
                }
                treeData.setData(arr_leftTree1);
                cFormName.setValue(edit_data[0].cFormName);
                // formTypes.setValue(edit_data[0].formTypes);
                // formTypes.doValueChanged();
                cLayoutType.setValue(edit_data[0].cLayoutType);
                cLayoutType.doValueChanged();
                modularId = edit_data[0].modularId;
                modular = edit_data[0].modular;
                buttons = edit_data[0].buttons;
                //获取ctree数据
                cTreeData = $.parseJSON(edit_data[0].cTree);
                parId = edit_data[0].parId;
                openId = edit_data[0].openId;
                var length = edit_data.length;
                var gridId_arr = [];
                var gridTabId_arr = [];
                var arr_eidt_tabs = [];//编辑模式下，页签内组件数组，用于保证页签先生成
                for(var k=0;k<length;k++) {
                    editFlag = true;
                    if(edit_data[k].type == 'table') {//表格
                        if(gridId_arr.indexOf(edit_data[k].c_id) == -1) {//表格未创建
                            gridId_arr.push(edit_data[k].c_id);
                            create(edit_data[k].type, [$.parseJSON(edit_data[k].gridColumns),edit_data[k].c_id] );
                            setPosition('table', edit_data[k].c_id, edit_data[k].iConX, edit_data[k].iConY, edit_data[k].iWidth, '', edit_data[k].iLabHeight);
                        }
                    }else if(edit_data[k].type == 'tab') {//页签
                        if(tabsId_arr.indexOf(edit_data[k].c_id) == -1) {//tab未创建
                            tabsId_arr.push(edit_data[k].c_id);
                            create(edit_data[k].type, {data:edit_data[k],i:k});
                            setPosition(edit_data[k].type, edit_data[k].c_id, edit_data[k].iConX, edit_data[k].iConY, edit_data[k].iWidth, edit_data[k].iLabWidth, edit_data[k].iLabHeight);
                        }else {//tab已创建，插入
                            addTab({id: edit_data[k].c_id},{action:'edit',
                                title:edit_data[k].cTabText,name:edit_data[k].tab_id});
                        }
                    }else if(edit_data[k].type.indexOf('tab_')>-1) {//页签组件
                        arr_eidt_tabs.push(edit_data[k]);
                    }else {//主表组件
                        create(edit_data[k].type, {data:edit_data[k],i:k});
                        setPosition(edit_data[k].type, edit_data[k].c_id, edit_data[k].iConX, edit_data[k].iConY, edit_data[k].iWidth, edit_data[k].iLabWidth, edit_data[k].iLabHeight);
                    }
                    if(edit_data[k].cMath != "") {
                        edit_data[k].cMath = $.parseJSON(edit_data[k].cMath);
                    }
                }
                for(var p=0;p<arr_eidt_tabs.length;p++) {
                    if(arr_eidt_tabs[p].type == 'tab_table') {//页签表格
                        if(gridTabId_arr.indexOf(arr_eidt_tabs[p].c_id) == -1) {//表格未创建
                            gridTabId_arr.push(arr_eidt_tabs[p].c_id);
                            insertTable({id:arr_eidt_tabs[p].tabs_id,tab_id:arr_eidt_tabs[p].tab_id,edit_data:$.parseJSON(arr_eidt_tabs[p].gridColumns),edit_id:arr_eidt_tabs[p].c_id});
                            // create(arr_eidt_tabs[p].type, [$.parseJSON(arr_eidt_tabs[p].gridColumns),arr_eidt_tabs[p].c_id] );
                            setPosition('table', arr_eidt_tabs[p].c_id, arr_eidt_tabs[p].iConX, arr_eidt_tabs[p].iConY, arr_eidt_tabs[p].iWidth, '', arr_eidt_tabs[p].iLabHeight);
                        }
                    }else {//页签其它组件
                        insertBase({id:arr_eidt_tabs[p].tabs_id,tab_id:arr_eidt_tabs[p].tab_id,edit_data:{data:arr_eidt_tabs[p],i:k}},arr_eidt_tabs[p].type.match(/tab_(\S*)/)[1]);
                        setPosition(arr_eidt_tabs[p].type, arr_eidt_tabs[p].c_id, arr_eidt_tabs[p].iConX, arr_eidt_tabs[p].iConY, arr_eidt_tabs[p].iWidth, arr_eidt_tabs[p].iLabWidth, arr_eidt_tabs[p].iLabHeight);
                    }
                }

                function setPosition(type,id,x,y,w,lab_w,h) {
                    $('#'+ id).css({
                        clear: 'both',
                        left: x,
                        top: y,
                        width: w,
                        height: h,
                        position: "absolute"
                    })
                    if(type == 'table') {

                    }else if(type.indexOf('formname')>-1) {

                    }else {
                        $('#lab'+ id).css({
                            left: w - lab_w
                        })
                        $('#left'+ id).css({
                            width: w - lab_w,
                            // height: h - 2
                        })
                        $('#right'+ id).css({
                            width: lab_w -5 ,
                            // height: h - 2,
                            left: w - lab_w + 3
                        })
                        $('#left'+ id).css({
                            width: w - lab_w,
                            // height: h - 2
                        })
                    }
                    // $("#"+id).offset({top: y + $("#north").height(), left: x + $("#west")});
                    // $("#"+thisId).offset({top: offsetY + $("#north").height(), left: offsetX + $("#west").width()});
                    // console.log(offsetX,offsetY);
                }
                editFlag = false;
            }
        },
        error : function(data){
        }
    });
}

//创建组件
function create(type,edit_data,coordinates,record) {

    if (type == 'textbox') { // 文本框
        create_textbox('mainField',edit_data,'',coordinates,record);
    } else if (type == 'textarea') { // 文本域
        create_textarea('mainField',edit_data,'',coordinates,record);
    } else if (type == 'fileupload') { // 附件
        create_fileupload('mainField',edit_data,'',coordinates,record);
    } else if (type == 'formname') { // 文本
        create_formname('mainField',edit_data,'',coordinates,record);
    } else if (type == 'spinner') { // 数值
        create_spinner('mainField',edit_data,'',coordinates,record);
    } else if (type == 'datepicker') { //时间
        create_datepicker('mainField',edit_data,'',coordinates,record);
    } else if (type == 'combobox') {//下拉框
        create_combobox('mainField',edit_data,'',coordinates,record);
    } else if (type == 'checkbox') {//复选框
        create_checkbox('mainField',edit_data,'',coordinates,record);
    } else if (type == 'buttonedit') {//参照
        create_buttonedit('mainField',edit_data,'',coordinates,record);
    } else if (type == 'tab') {//页签
        create_tabs('mainField',edit_data,'',coordinates,record);
    } else if (type == 'table') {//表格
        if(editFlag) {
            create_table('mainField',edit_data[0],edit_data[1]);
        }else {
            create_table('mainField','','','',coordinates,record);
        }

    }
}

/**---------------------------------------操作textbox start----------------------------------------*/
//创建文本框
//param: 页签插入组件的参数
// var textbox_index = 0;
function create_textbox(area,edit_data,param,coordinates,record) {

    var cTableFieldType;
    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;//全称
        var id = thisId.substring(thisId.indexOf("_")+1);//数字
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        textbox_editIndex.push(id);
        textbox_index = Math.max.apply(null, textbox_editIndex);//最大的值作为新建组件的id起点
        cTableFieldType = properties[edit_data.i].cTableFieldType;
    }else {
        textbox_index++;
        id = textbox_index;//数字
        thisId = 'textbox_' + id;//全称
        cTableFieldType = record.cTableFieldType;

        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: record.name,//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'textbox'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: record.name,//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_textbox'
            });
        }
    }

    var $clone = "<div class='box box-textbox dragbox' id='textbox_" + id + "'>" +
        // "  <li style='width: 95px;float: left;height: 100%;background: #ccc;overflow: hidden;text-align: center;line-height: 40px;' id='li" + id + "'></li>" +
        "  <div class='left' id='left" + thisId + "'><p class='text'>textbox</p></div>" +
        "  <label class='lab1' id='lab" + thisId + "'></label>" +
        "  <div class='right' id='right" + thisId + "'>" +
        "       <input id='text"+id+"' class='mini-textbox' emptyText='' />" +
        "  </div>" +
        "</div>";
    var contextmenu = "<ul id='textboxMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";
    var type;//页签组件或非页签组件类型
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'textbox';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    "margin-left": 10,
                    "margin-bottom": 6
//                    clear: 'both', left: coordinates.x,
//                    top: coordinates.y, position: "absolute"
                })
            }
        }
    }else {
        $(param.area).append($clone);
        $(param.area).append(contextmenu);
        type = 'tab_textbox';
    }

    mini.parse();
    //  click_id= thisId;

    $("#textbox_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("textboxMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });

    resize_base("textbox_" + id);

    $("#"+thisId).on('mouseup',function(e){ //点击事件(鼠标松开时发生)
        //click事件里去检测这个变量是否发生改变，如果没改变，说明mouseup刚执行完，这里不执行
        //mouseup事件里定时改变一个变量
        window.mouseup_click_debug = true;
        setTimeout(function() {
            window.mouseup_click_debug = false;
        }, 200);
        baseClick(e,type,thisId,cTableFieldType);
    });

    setEditBoxText('textbox',thisId);//编辑模式时设置组件名称

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

    }else {
        click_id = thisId;
        cTableField.setValue(record.name);
        cTableField_ch.setValue(record.name_ch);
        cLadText.setValue(record.text);
        cComType.setValue(type);
        cLadText.doValueChanged();

        baseClick('',type,thisId,cTableFieldType);
    }


}

/**---------------------------------------操作textbox end----------------------------------------*/


/**---------------------------------------操作textarea start-------------------------------------*/
//创建文本域
// var textarea_index = 0;
function create_textarea(area,edit_data,param,coordinates,record) {

    var cTableFieldType;
    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;
        var id = thisId.substring(thisId.indexOf("_")+1);
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        textarea_editIndex.push(id);
        textarea_index = Math.max.apply(null, textarea_editIndex);
        cTableFieldType = properties[edit_data.i].cTableFieldType;
    }else {
        textarea_index++;
        id = textarea_index;//数字
        thisId = 'textarea_'+id;//全称
        cTableFieldType = record.cTableFieldType;
        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: record.name,//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'textarea'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: record.name,//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_textarea'
            });
        }
    }

    var $clone = "<div class='box box-textarea dragbox' id='textarea_" + id + "'>" +
        "  <div class='left' id='left" + thisId + "'><p class='text'>texterea</p></div>" +
        "  <label class='lab1' id='lab" + thisId + "'></label>" +
        "  <div class='right' id='right" + thisId + "'>" +
        "     <textarea class='mini-textarea' emptyText=''></textarea>" +
        "  </div>" +
        "</div>";
    var contextmenu = "<ul id='textareaMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";
    var type;
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'textarea';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    "margin-left": 10,
                    "margin-bottom": 6
//                    clear: 'both', left: coordinates.x,
//                    top: coordinates.y, position: "absolute"
                })
            }
        }
    }else {
        $(param.area).append($clone);
        $(param.area).append(contextmenu);
        type = 'tab_textarea';
    }
    mini.parse();
    // click_id = thisId;
    $("#textarea_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("textareaMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });
    resize_base("textarea_" + id);
    $("#"+thisId).on('mouseup',function(e){
        baseClick(e,type,thisId,cTableFieldType)
    });

    setEditBoxText('textarea',thisId);//编辑模式时设置组件名称

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

    }else {
        click_id= thisId;
        cTableField.setValue(record.name);
        cTableField_ch.setValue(record.name_ch);
        cLadText.setValue(record.text);
        cComType.setValue(type);
        cLadText.doValueChanged();

        baseClick('',type,thisId,cTableFieldType);
    }

}

/**---------------------------------------操作textarea end-----------------------------*/

/**---------------------------------------操作fileupload start-------------------------------------*/
//创建附件
// var fileupload_index = 0;
function create_fileupload(area,edit_data,param,coordinates,record) {

    var cTableFieldType;
    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;
        var id = thisId.substring(thisId.indexOf("_")+1);
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        fileupload_editIndex.push(id);
        fileupload_index = Math.max.apply(null, fileupload_editIndex);
        cTableFieldType = properties[edit_data.i].cTableFieldType;
    }else {
        fileupload_index++;
        id = fileupload_index;//数字
        thisId = 'fileupload_'+id;//全称
        cTableFieldType = record.cTableFieldType;
        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: record.name,//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'fileupload'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: record.name,//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_fileupload'
            });
        }
    }

    var $clone = "<div class='box box-buttonedit dragbox' id='fileupload_" + id + "'>" +
        "  <div class='left' id='left" + thisId + "'><p class='text'>fileupload</p></div>" +
        "  <label class='lab1' id='lab" + thisId + "'></label>" +
        "  <div class='right' id='right" + thisId + "'>" +
        "   <input id='upload" + id + "' class='mini-fileupload' name='Fdata' limitType='' \n" +
        "    flashUrl='swfupload/swfupload.swf'\n" +
        // "    uploadUrl='/enclosure/uploadFile.do'\n" +
        // "    onuploadsuccess='onUploadSuccess' \n" +
        // "    onuploaderror='onUploadError' onfileselect='onFileSelect'\n" +
        "    />" +
        "  </div>" +
        "</div>";
    var contextmenu = "<ul id='fileuploadMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";
    var type;
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'fileupload';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    "margin-left": 10,
                    "margin-bottom": 6
//                    clear: 'both', left: coordinates.x,
//                    top: coordinates.y, position: "absolute"
                })
            }
        }
    }else {
        $(param.area).append($clone);
        $(param.area).append(contextmenu);
        type = 'tab_fileupload';
    }
    mini.parse();
    // click_id = thisId;
    $("#fileupload_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("fileuploadMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });
    resize_base("fileupload_" + id);
    $("#"+thisId).on('mouseup',function(e){
        baseClick(e,type,thisId,cTableFieldType)
    });

    setEditBoxText('fileupload',thisId);//编辑模式时设置组件名称

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

    }else {
        click_id= thisId;
        cTableField.setValue(record.name);
        cTableField_ch.setValue(record.name_ch);
        cLadText.setValue(record.text);
        cComType.setValue(type);
        cLadText.doValueChanged();

        baseClick('',type,thisId,cTableFieldType);
    }

}

/**---------------------------------------操作fileupload end-----------------------------*/


/**---------------------------------------操作formname start-------------------------------------*/
//创建标题
// var formname_index = 0;
function create_formname(area,edit_data,param,coordinates,record) {

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;
        var id = thisId.substring(thisId.indexOf("_")+1);
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        formname_editIndex.push(id);
        formname_index = Math.max.apply(null, formname_editIndex);

    }else {
        formname_index++;
        id = formname_index;//数字
        thisId = 'formname_'+id;//全称
        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cFormName: '',//表单名
                cTableFieldType: '',//字符类型
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: '',//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'formname'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cFormName: '',//表单名
                cTableFieldType: '',//字符类型
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: '',//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_formname'
            });
        }
    }

    var $clone = "<div class='box-formname dragbox' id='formname_" + id + "'>" +
        //         "  <div class='left' id='left" + thisId + "'><p class='text'>texterea</p></div>" +
        // "  <label class='lab1' id='lab" + thisId + "'></label>" +
        //        "  <div class='right' id='right" + thisId + "'>" +
        //         "     <textbox class='mini-textbox' id='rightformname_" + id + "' emptyText=''></textbox>" +
        //        "  </div>" +
        "  <div class='' id='right" + thisId + "'><p class='text'></p></div>" +

        "</div>";
    var contextmenu = "<ul id='formnameMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";
    var type;
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'formname';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            $('#' + thisId).css({
                clear: 'both', left: coordinates.x,
                top: coordinates.y, position: "absolute"
            })
        }
    }else {
        $(param.area).append($clone);
        $(param.area).append(contextmenu);
        type = 'tab_formname';
    }
    mini.parse();
    // click_id = thisId;
    //绑定右键菜单
    $("#formname_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("formnameMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });
    $("#right"+thisId).css({
        "text-align": "center"
    });
    resize_base("formname_" + id);
    $("#"+thisId).on('mouseup',function(e){
        baseClick(e,type,thisId,type)
    });

    setEditBoxText('formname',thisId);//编辑模式时设置组件名称

}

/**---------------------------------------操作formname end-----------------------------*/


/**---------------------------------------操作datepicker start-------------------------------------*/
//创建时间选择器
// var datepicker_index = 0;
function create_datepicker(area,edit_data,param,coordinates,record) {

    var cTableFieldType;
    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;
        var id = thisId.substring(thisId.indexOf("_")+1);
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        datepicker_editIndex.push(id);
        datepicker_index = Math.max.apply(null, datepicker_editIndex);
        cTableFieldType = properties[edit_data.i].cTableFieldType;

    }else {
        datepicker_index++;
        id = datepicker_index;//数字
        thisId = 'datepicker_'+id;//全称
        cTableFieldType = record.cTableFieldType;
        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                cCombo: '',//自定义下拉框内容
                ref: {},//参照总数据
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'datepicker'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_datepicker'
            });
        }
    }

    var $clone = "<div class='box box-datepicker dragbox' id='datepicker_" + id + "'>" +
        "  <div class='left' id='left" + thisId + "'><p class='text'>datepicker</p></div>" +
        "  <label class='lab1' id='lab" + thisId + "'></label>" +
        "  <div class='right' id='right" + thisId + "'>" +
        "    <input id='date" + id + "'class='mini-datepicker' value=''/>" +
        "  </div>" +
        "</div>";
    var contextmenu = "<ul id='datepickerMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";

    var type;
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'datepicker';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    "margin-left": 10,
                    "margin-bottom": 6
//                    clear: 'both', left: coordinates.x,
//                    top: coordinates.y, position: "absolute"
                })
            }
        }
    }else {
        $(param.area).append($clone);
        $(param.area).append(contextmenu);
        type = 'tab_datepicker';
    }
    mini.parse();
    // click_id = thisId;
    setEditBoxText('datepicker',thisId);//编辑模式时设置组件名称

    $("#datepicker_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("datepickerMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });
    // disableDate("date" + id);
    resize_base(thisId);
    $("#"+thisId).on('mouseup',function(e){
        baseClick(e,type,thisId,cTableFieldType)
    });
    mini.get("date"+id).on('valuechanged',function(e){//组件值恒为空
        e.sender.setValue("");
    });

    setEditBoxText('textbox',thisId);//编辑模式时设置组件名称

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

    }else {
        click_id= thisId;
        cTableField.setValue(record.name);
        cTableField_ch.setValue(record.name_ch);
        cLadText.setValue(record.text);
        cComType.setValue(type);
        cLadText.doValueChanged();

        baseClick('',type,thisId,cTableFieldType);
    }

}

//禁用
// function disableDate(id) {
//     var date = mini.get(id+'');
//     date.disable();
// }

/**---------------------------------------操作datepicker end---------------------*/

/**---------------------------------------操作spinner start-------------------------------------*/
//创建数值
// var spinner_index = 0;
function create_spinner(area,edit_data,param,coordinates,record) {

    var cTableFieldType;
    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;
        var id = thisId.substring(thisId.indexOf("_")+1);
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        spinner_editIndex.push(id);
        spinner_index = Math.max.apply(null, spinner_editIndex);
        cTableFieldType = properties[edit_data.i].cTableFieldType;
    }else {
        spinner_index++;
        id = spinner_index;//数字
        thisId = 'spinner_'+id;//全称
        cTableFieldType = record.cTableFieldType;
        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'spinner'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_spinner'
            });
        }
    }

    var $clone = "<div class='box box-spinner dragbox' id='spinner_" + id + "'>" +
        "  <div class='left' id='left" + thisId + "'><p class='text'>spinner</p></div>" +
        "  <label class='lab1' id='lab" + thisId + "'></label>" +
        "  <div class='right' id='right" + thisId + "'>" +
        "    <input id='spin"+id+"' class='mini-spinner' decimalPlaces='2' allowNull='true'/>"+
        "  </div>" +
        "</div>";
    var contextmenu = "<ul id='spinnerMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";

    var type;
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'spinner';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    "margin-left": 10,
                    "margin-bottom": 6
//                    clear: 'both', left: coordinates.x,
//                    top: coordinates.y, position: "absolute"
                })
            }
        }
    }else {
        $(param.area).append($clone);
        $(param.area).append(contextmenu);
        type = 'tab_spinner';
    }
    mini.parse();
    // click_id = thisId;
    setEditBoxText('spinner',thisId);//编辑模式时设置组件名称

    $("#spinner_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("spinnerMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });
    // disableDate("date" + id);
    resize_base(thisId);
    $("#"+thisId).on('mouseup',function(e){
        baseClick(e,type,thisId,cTableFieldType)
    });
//    mini.get("spin"+id).on('valuechanged',function(e){//组件值恒为空
//        e.sender.setValue("");
//    });

    setEditBoxText('spinner',thisId);//编辑模式时设置组件名称

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

    }else {
        click_id= thisId;
        cTableField.setValue(record.name);
        cTableField_ch.setValue(record.name_ch);
        cLadText.setValue(record.text);
        cComType.setValue(type);
        cLadText.doValueChanged();

        baseClick('',type,thisId,cTableFieldType);
    }

}


/**---------------------------------------操作spinner end---------------------*/


/**---------------------------------------参照 start-------------------------------*/
//创建
// var buttonedit_index = 0;
function create_buttonedit(area,edit_data,param,coordinates,record) {

    var cTableFieldType;
    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;
        var id = thisId.substring(thisId.indexOf("_") + 1);
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        buttonedit_editIndex.push(id);
        buttonedit_index = Math.max.apply(null, buttonedit_editIndex);
        cTableFieldType = properties[edit_data.i].cTableFieldType;
    }else {
        buttonedit_index++;
        id = buttonedit_index;//数字
        thisId = 'buttonedit_'+id;//全称
        cTableFieldType = record.cTableFieldType;
        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                cReference: '',//参照
                cBgReference: '',//后台参照
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'buttonedit'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                cReference: '',//参照
                cBgReference: '',//后台参照
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_buttonedit'
            });
        }
    }
    var $clone = "<div class='box box-buttonedit dragbox' id='buttonedit_" + id + "'>" +
        "  <div class='left' id='left" + thisId + "'><p class='text'>buttonedit</p></div>" +
        "  <label class='lab1' id='lab" + thisId + "'></label>" +
        "  <div class='right' id='right" + thisId + "'>" +
        "   <input id='look"+id+"' class='mini-buttonedit' emptyText='' />" +
        "</div></div>";
    var contextmenu = "<ul id='buttoneditMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";

    var type;
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'buttonedit';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    "margin-left": 10,
                    "margin-bottom": 6
//                    clear: 'both', left: coordinates.x,
//                    top: coordinates.y, position: "absolute"
                })
            }
        }
    }else{
        $(param.area).append($clone);
        $(param.area).append(contextmenu);
        type = 'tab_buttonedit';
    }

    mini.parse();
    // click_id = thisId;

    $("#buttonedit_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("buttoneditMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });
    $("#" + thisId).draggable({
        containment: "parent",
        // containment: "#mainField",
        scroll: false,
        cursor: "move"
    });
    resize_base(thisId);
    $("#"+thisId).on('mouseup',function(e){
        baseClick(e,type,thisId,cTableFieldType)
    });

    setEditBoxText('buttonedit',thisId);//编辑模式时设置组件名称

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

    }else {
        click_id= thisId;
        cTableField.setValue(record.name);
        cTableField_ch.setValue(record.name_ch);
        cLadText.setValue(record.text);
        cComType.setValue(type);
        cLadText.doValueChanged();

        baseClick('',type,thisId,cTableFieldType);
    }

}

//参照弹窗
cReference.on("focus", function (e) {
    onBindRef('ref');
})
// //后台参照
// cBgReference.on("focus", function (e) {
//     onBindRef('refBg');
// })

// 表单设计器参照跳转
var referData = [];//挂到左侧数据项的数据
function onBindRef(type) {
    mini.open({
        url : bootPATH + "../frame/frame1/pages/formDesign/bindRef.html",
        title : "选择参照",
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = {};
            var param;
            if(click_type == 'table' || click_type == 'tab_table') {
                param = 'col_id'
            }else {
                param = 'c_id'
            }
            for(var i=0;i<properties.length;i++) {
                if (properties[i][param] == click_id) {
                    if(type == 'ref') {
                        data = properties[i].ref.ref;
                    }else {
                        data = properties[i].ref.refBg;
                    }
                }
            }
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                referData = data.referData;
                data = mini.clone(data.record);
                console.log(data,'bindRef');
                console.log(referData,'referData');

                // 选择参照后左侧树列表增加所参照表的数据
                // for(var m=0;m<referData.length;m++) {
                //     referData[m].id = referData[m].field;
                //     referData[m].name = referData[m].field;
                //     referData[m].name_ch = referData[m].fieldCh;
                //     referData[m].text = referData[m].fieldCh;
                //     referData[m].ptype = 'main';
                //     referData[m].isTableName = false;
                // }
                // var referTree = [];
                // referTree.push({
                //     field: data.cFormName,
                //     fieldCh: data.cFormName,
                //     id: data.cFormName,
                //     isTableName: true,
                //     name: data.cFormName,
                //     name_ch: data.cFormName,
                //     ptype: "main",
                //     text: data.cFormName,
                //     type: "",
                //     cTableName: data.cTableName,
                //     formListId: data.formListId,
                //     mTableId: 0,
                //     pid: 0,
                //     children: referData
                // });
                // console.log(referTree,'referTree');
                // var allData = treeData.getData();
                // var addFlag = true;
                // for(var k=0;k<allData.length;k++) {
                //     if(referTree[0].cTableName == allData[k].cTableName) {
                //         addFlag = false;
                //     }
                // }
                // if(addFlag) {
                //     allData[allData.length] = referTree[0]
                //     console.log(allData);
                //     treeData.setData(allData);
                // }

                var param;
                if(click_type == 'table' || click_type == 'tab_table') {
                    param = 'col_id'
                }else {
                    param = 'c_id'
                }
                for(var i=0;i<properties.length;i++) {
                    if(properties[i][param] == click_id) {
                        if(type == 'ref') {
                            cReference.setValue(data.cLadText);
                            properties[i].ref.ref = data;
                        }else {
                            // cBgReference.setValue(data.cLadText);
                            properties[i].ref.refBg = data;
                        }
                    }
                }
                // cLadText.doValueChanged();//主动激发valuechanged事件
            }
        }
    })
}
/**---------------------------------------参照 end--------------------------------------------*/


/**---------------------------------------下拉框 start----------------------------------------*/
// var combobox_index = 0;
function create_combobox(area,edit_data,param,coordinates,record) {

    var cTableFieldType;
    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;
        var id = thisId.substring(thisId.indexOf("_")+1);
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        combobox_editIndex.push(id);
        combobox_index = Math.max.apply(null, combobox_editIndex);
        cTableFieldType = properties[edit_data.i].cTableFieldType;
    }else {
        combobox_index++;
        id = combobox_index;//数字
        thisId = 'combobox_'+id;//全称
        cTableFieldType = record.cTableFieldType;
        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'combobox'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cCombo: '',//自定义下拉框内容
                cCheckbox: '',//自定义复选框内容
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_combobox'
            });
        }
    }

    var $clone = "<div class='box box-combobox dragbox' id='combobox_" + id + "'>" +
        // "  <li style='width: 95px;float: left;height: 100%;background: #ccc;overflow: hidden;text-align: center;line-height: 40px;' id='li" + id + "'></li>" +
        "  <div class='left' id='left" + thisId + "'><p class='text'>combobox</p></div>" +
        "  <label class='lab1' id='lab" + thisId + "'></label>" +
        "  <div class='right' id='right" + thisId + "'>" +
        "    <input id='combo"+id+"' class='mini-combobox' style=''" +
        "     textField='text' valueField='id' value=''\n" +
        "     showNullItem='true' allowInput='false'/>" +
        " </div>" +
        "</div>";

    var type;
    var contextmenu = "<ul id='comboboxMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'combobox';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    "margin-left": 10,
                    "margin-bottom": 6
//                    clear: 'both', left: coordinates.x,
//                    top: coordinates.y, position: "absolute"
                })
            }
        }
    }else {
        $(param.area).append($clone);
        $(param.area).append(contextmenu);
        type = 'tab_combobox';
    }
    mini.parse();
    // click_id = thisId;

    $("#combobox_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("comboboxMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });

    resize_base("combobox_" + id);
    $("#"+thisId).on('mouseup',function(e){
        baseClick(e,type,thisId,cTableFieldType)
    });

    setEditBoxText('combobox',thisId);//编辑模式时设置组件名称

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

    }else {
        click_id= thisId;
        cTableField.setValue(record.name);
        cTableField_ch.setValue(record.name_ch);
        cLadText.setValue(record.text);
        cComType.setValue(type);
        cLadText.doValueChanged();

        baseClick('',type,thisId,cTableFieldType);
    }

}

/**---------------------------------------下拉框 end----------------------------------------*/


/**---------------------------------------复选框 start----------------------------------------*/
//创建
// var checkbox_index = 0;
function create_checkbox(area,edit_data,param,coordinates,record) {

    var cTableFieldType;
    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        var thisId = edit_data.data.c_id;
        var id = thisId.substring(thisId.indexOf("_")+1);
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        checkbox_editIndex.push(id);
        checkbox_index = Math.max.apply(null, checkbox_editIndex);
        cTableFieldType = properties[edit_data.i].cTableFieldType;
    }else {
        checkbox_index++;
        id = checkbox_index;//数字
        thisId = 'checkbox_'+id;//全称
        cTableFieldType = record.cTableFieldType;
        if(area == 'mainField') {
            properties.push({
                c_id: thisId,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'checkbox'
            });
        }else {//页签插入
            properties.push({
                c_id: thisId,
                tabs_id: param.c_id,
                tab_id: param.tab_id,
                cLadText: '',//字段中文名
                cTableField: '',//字段英文名(唯一)
                cTableField_ch: '',
                cTableFieldType: record.cTableFieldType,//字符类型
                cFormName: '',//表单名
                cLength: '',//自定义长度
                ref: {},//参照总数据
                cGridType: '',//自定义列类型
                cGroup: '',//自定义列分组
                cMath: '',//公式
                cRefObj: {},
                cTableName: record.tableName,//数据库表名(英文)
                tableClassName: '',//数据库表名(中文)
                iConX: '',
                iConY: '',
                iLabHeight: '',
                iWidth: '',
                iLabWidth: '',
                cEditCss: '',
                lanyoutMent: '',
                type: 'tab_checkbox'
            });
        }
    }

    // var $clone = "<div class='box-checkbox' id='checkbox_"+id+"'>" +
    //     "<div id='check_"+id+"' name='' class='mini-checkbox' readOnly='false' text='checkBox'></div>" +
    //     "</div>";
    // var $clone = "<div class='box-checkbox' id='checkbox_"+id+"'>" +
    //     "<div id='check_"+id+"' name='' class='mini-checkboxlist' ></div>" +
    //     "</div>";

    var $clone = "<div class='box box-checkbox dragbox' id='checkbox_" + id + "'>" +
        // "  <li style='width: 95px;float: left;height: 100%;background: #ccc;overflow: hidden;text-align: center;line-height: 40px;' id='li" + id + "'></li>" +
        "  <div class='left' id='left" + thisId + "'><p class='text'>checkbox</p></div>" +
        "  <label class='lab1' id='lab" + thisId + "'></label>" +
        "  <div class='right' id='right" + thisId + "'>" +
        "    <div id='check"+id+"' name='' class='mini-checkboxlist' ></div>" +
        "  </div>" +
        "</div>";
    var contextmenu = "<ul id='checkboxMenu" + id + "' class='mini-contextmenu'>\n" +
        "    <li onclick='removeBox(" + thisId + ")'>删除</li>\n" +
        "</ul>";

    var type;
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextmenu);
        type = 'checkbox';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    "margin-left": 10,
                    "margin-bottom": 6
//                    clear: 'both', left: coordinates.x,
//                    top: coordinates.y, position: "absolute"
                })
            }
        }
    }else if(area == 'checkbox') {
        $(param).append($clone);
        $(param).append(contextmenu);
        type = 'tab_checkbox';
    }

    mini.parse();
    // click_id = thisId;

//     mini.get('check'+id).setData([
//         { "id": "", "text": "" }
//     ]);

    $("#checkbox_"+id).bind("contextmenu", function (e) {
        var menu = mini.get("checkboxMenu"+id);
        menu.showAtPos(e.pageX, e.pageY);
        return false;
    });
    $("#" + thisId).draggable({
        containment: "parent",
        // containment: "#mainField",
        scroll: false,
        cursor: "move"
    });

    // $("#" + thisId).resizable({
    //     handles: 'n, e, s, w, ne, se, sw, nw',
    //     grid: [2, 2],
    //     resize: function () {
    //         $("#" + thisId).css({
    //             "min-height": $("#" + thisId+' span.mini-checkbox').height(),
    //             "min-width": $("#" + thisId+' span.mini-checkbox').width() +20
    //         })
    //     }
    // });
    resize_base(thisId);
    $("#"+thisId).on('mouseup',function(e){
        baseClick(e,type,thisId,cTableFieldType);
    });

    setEditBoxText('checkbox',thisId);//编辑模式时设置组件名称

    if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

    }else {
        click_id= thisId;
        cTableField.setValue(record.name);
        cTableField_ch.setValue(record.name_ch);
        cLadText.setValue(record.text);
        cComType.setValue(type);
        cLadText.doValueChanged();

        baseClick('',type,thisId,cTableFieldType);
    }

}

/**---------------------------------------复选框 end-------------------------------------*/


/**---------------------------------------操作表格 start----------------------------------------*/
//创建表格
// var table_index = 0;
var gridClick_num = -1;
function create_table(area,edit_data,edit_id,param,coordinates,records) {
    // table_index++;
    // var id = table_index;
    var thisId;
    var cols = [];
    if(action == 'edit' && editFlag || param.type == 'bind') {
        cols = edit_data;
        thisId = edit_id;
        id = thisId.substring(thisId.indexOf("_")+1);
        if(param != undefined) {
            if(param.type == 'bind') {//页签绑定表格
                id = edit_id;
                thisId = 'datagrid_'+id;//全称
            }
        }
        // thisId = edit_id;
        // var id = thisId.substring(thisId.indexOf("_")+1);
        // table_editIndex.push(id);
        // table_index = Math.max.apply(null, table_editIndex);
    }else {
        table_index++;
        // id = table_index;//数字
        id = records[0].tableName;
        thisId = 'datagrid_'+id;//全称
        for(var p=0;p<records.length;p++) {
            if(records[p].checked == true) {
                cols.push({
                    // field: thisId + '$' + records[p].id,
                    field: records[p].id,
                    header: records[p].text,
                    name: records[p].id, width: 100, headerAlign: "center", allowSort: false,allowMoveColumn:false,
                    editor: { type: "textbox"},type: records[p].type,tableName:records[p].tableName
                })
            }
        }
        for(var i=0;i<cols.length;i++) {
            if(area == 'mainField') {
                properties.push({
                    c_id: thisId,//表格id
                    col_id: cols[i].field,//列id
                    cLadText: cols[i].header,//字段中文名
                    cTableField: cols[i].name,//字段英文名(唯一)
                    cTableField_ch: cols[i].header,
                    cTableFieldType: cols[i].cTableFieldType,//字符类型
                    cFormName: '',//表单名
                    cLength: '',//自定义长度
                    cCombo: '',//自定义下拉框内容
                    cCheckbox: '',//自定义复选框内容
                    cGridType: 'textbox',//自定义列类型
                    cGroup: '',//自定义列分组
                    cReference: '',
                    cBgReference: '',
                    ref: {},
                    cMath: '',//公式
                    cRefObj: {
                        cLadText: cols[i].header,
                        cTableField: cols[i].name,
                        cTableField_ch: cols[i].header
                    },
                    cTableName: cols[i].tableName,//数据库表名(英文)
                    tableClassName: '',//数据库表名(中文)
                    iConX: '',
                    iConY: '',
                    iLabHeight: '',
                    iWidth: '',
                    iLabWidth: '',
                    cEditCss: '',
                    lanyoutMent: '',
                    type: 'table'
                });
            }else {//页签插入
                properties.push({
                    c_id: thisId,//表格id
                    col_id: cols[i].field,//列id
                    tabs_id: param.c_id,
                    tab_id: param.tab_id,
                    cLadText: cols[i].header,//字段中文名
                    cTableField: cols[i].name,//字段英文名(唯一)
                    cTableField_ch: cols[i].header,
                    cTableFieldType: cols[i].cTableFieldType,//字符类型
                    cFormName: '',//表单名
                    cLength: '',//自定义长度
                    cCombo: '',//自定义下拉框内容
                    cCheckbox: '',//自定义复选框内容
                    cGridType: 'textbox',//自定义列类型
                    cGroup: '',//自定义列分组
                    cReference: '',
                    cBgReference: '',
                    ref: {},
                    cMath: '',//公式
                    cRefObj: {
                        cLadText: cols[i].header,
                        cTableField: cols[i].name,
                        cTableField_ch: cols[i].header
                    },
                    cTableName: cols[i].tableName,//数据库表名(英文)
                    tableClassName: '',//数据库表名(中文)
                    iConX: '',
                    iConY: '',
                    iLabHeight: '',
                    iWidth: '',
                    iLabWidth: '',
                    cEditCss: '',
                    lanyoutMent: '',
                    type: 'tab_table'
                });
            }
        }
    }

    var $clone = "<div id='datagrid_" + id + "' class='mini-datagrid dragbox' style=''\n" +
        "     showPager=false multiSelect=false allowResize=true allowColumnSelect=true allowMoveColumn=false " +
        "     allowCellEdit=true allowCellSelect=true editNextOnEnterKey=true editNextRowCell=true "+
        "     headerContextMenu='#headerMenu" + id + "' contextMenu='#gridMenu" + id + "'>\n" +
        "    <div property='columns'></div>\n" +
        "</div>";
    var headerMenu = "<ul id='headerMenu" + id + "' class='mini-contextmenu'>\n" +
        // "    <li name='add' onclick='addGridCols(" + id + ")'>增加列</li>\n" +
        "    <li name='remove' onclick='bindTab(" + thisId + ")'>绑定页签</li>\n" +
        "    <li name='remove' onclick='removeGridCols(" + thisId + ")'>删除列</li>\n" +
        "    <li name='delAll' onclick='removeAllGridCols(" + thisId + ")'>全部删除</li>\n" +
        // "    <li><span >列类型</span><ul>" +
        // "    <li name='set' onclick=\"setGridColEditor(" + id + ",'textbox')\">文本</li>\n" +
        // "    <li name='set' onclick=\"setGridColEditor(" + id + ",'textarea')\">文本域</li>\n" +
        // "    <li name='set' onclick=\"setGridColEditor(" + id + ",'combobox')\">下拉框</li>\n" +
        // "    <li name='set' onclick=\"setGridColEditor(" + id + ",'datepicker')\">时间</ul></li>\n" +
        "</ul>";

    var gridMenu = "<ul id='gridMenu" + id + "' class='mini-contextmenu' onbeforeopen='onBeforeOpenGrid(e," + id + ")'>\n" +
        "    <li onclick='addGridRows(" + id + ")'>新增行</li>\n" +
        "    <li onclick='removeGridRows(" + id + ")'>删除行</li>\n" +
        // "    <li onclick='removeAllTab("+id+")'>全部删除</li>\n" +
        "</ul>";

    var type;
    if(area == 'tabs') {
        $(param.area).append($clone);
        $(param.area).append(headerMenu);
        $(param.area).append(gridMenu);
        type = 'tab_table';
    }else{
        $('#mainField').append($clone);
        $('#mainField').append(headerMenu);
        // $('#mainField').append(gridMenu);
        type = 'table';

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            if(coordinates.type == 'drag' || coordinates.type == 'compChanged') {
                $('#'+ thisId).css({
                    clear: 'both', left: coordinates.x,
                    top: coordinates.y, position: "absolute"
                })
            }else {//一键布局，不需要坐标
                $('#'+ thisId).css({
                    // "margin-top": 30,
//                    "margin-bottom": 30,
//                     "clear": "both"
                })
            }
        }
    }

    mini.parse();
    // click_id = thisId;

    setEditBoxText('table',thisId);//编辑模式时设置组件名称
    var grid = mini.get("datagrid_" + id);
    grid.set({
        columns: cols,
    })
    var data = [{}, {}];
    grid.setData(data);

    $("#" + thisId).draggable({
        containment: "parent",
        // containment: "#mainField",
        scroll: false,
        cursor: "move"
    });

    //点击表头事件
    grid.on("headercellclick", function (e) {
        // click_id = e.column.field;
        console.log(e.column,'column');
        grid_message = e;
        console.log(grid,'grid');
        if(e.column.columns != undefined && e.column.columns.length>0) {//表分组
            showProperty();
        }else {

            gridClick_num++;
            gridClick_id = id;

            gridClick(e,type);
            // cTableField.setValue(e.column.name);
            // cLadText.setValue(e.column.header);
            // cLadText.doValueChanged();
        }
    });

    //右击表头事件
    grid.on("headercellcontextmenu", function (e) {
        // console.log(e);
        rightClickCol = e.column;
        console.log(rightClickCol,'rightClickCol');
        gridClick(e,type);
    });

    //表头单元格鼠标按下时发生
    // grid.on("headercellmousedown", function (e) {
    //     // console.log(e);
    //     // rightClickCol = e.column;
    // });

}

//表格--点击表头
var c_id;//总id
function gridClick(e,type) {

    // $(".mini-grid-headerCell").css({
    //     background: "red"
    // });
    // e.htmlEvent.target.parentNode.style.background = '#b3d5ea';

    // if(e.column.name == 'header') {
    // 	return;
    // }
    stopBubbling(e,'table');//多个点击事件冲突处理
    cancelBlur();
    pre_click_type = click_type;
    pre_click_id = click_id;
    click_type = type;
    click_types.push(type);
    // click_id = e.column.field;//field是id英文,header是中文
    click_id = e.column.field;//name字段为固定
    click_ids.push(click_id);
    c_id = e.sender.id;//表格id
    console.log('pre:',pre_click_type,',',pre_click_id);
    console.log('now:',click_type,',',click_id);

    showProperty("table");

    savePre(pre_click_type,click_id,pre_click_id);

    // console.log(e.sender,'sender');//表格对象
    // var cols = e.sender.columns;//所有的列
    // var grid = mini.get(e.sender.id);
    // console.log(e.column, 'cols');//列对象
    //
    // for(var i=0;i<cols.length;i++) {
    //     if(cols[i].field == e.column.field) {
    //         cols[i].field = 'test';
    //         cols[i].header = '测试';
    //     }
    // }
    // grid.set({
    //     columns: cols
    // })
}
//表格--右键菜单
function onBeforeOpenGrid(e,id) {
    var grid = mini.get("datagrid"+id);
    var menu = e.sender;

    var row = grid.getSelected();
    // var rowIndex = grid.indexOf(row);
    if (!row) {
        e.cancel = true;
        e.htmlEvent.preventDefault();//阻止浏览器默认右键菜单
        return;
    }
    // var editItem = mini.getbyName("edit", menu);
    // editItem.show();
    // removeItem.enable();
}
//表格绑定页签
var arr_tabs = [];
function bindTab(e) {
    console.log(e);
    arr_tabs = [];
    for(var i=0;i<properties.length;i++) {
        if(properties[i].type == 'tab') {
            arr_tabs.push(properties[i]);
        }
    }
    console.log(arr_tabs,'arr_tabs');
    if(arr_tabs != []) {
        mini.open({
            url : bootPATH + "../frame/frame1/pages/formDesign/bindTab.html",
            title : "绑定页签",
            onload: function () {       //弹出页面加载完成
                var iframe = this.getIFrameEl();
                iframe.contentWindow.SetData(arr_tabs);
            },
            ondestroy: function (action) {  //弹出页面关闭前
                if (action == "ok") {
                    var iframe = this.getIFrameEl();
                    var data = iframe.contentWindow.onTableOk();
                    console.log(data);
                    var grid = mini.get('datagrid_'+rightClickCol.tableName);
                    var cols = grid.getColumns();
                    console.log(cols,'cols');
                    var insertData = {
                        id: data.c_id,
                        tab_id: data.tab_id,
                        edit_data: cols,
                        edit_id: rightClickCol.tableName
                    };
                    // 页签插入表格
                    insertTable(insertData,'bind');
                }
            }
        })
    }else {
        mini.alert("暂无可用页签！");
    }

}
//增列
var col_index = 2;
var _id_arr = [];
function addGridCols(id,record) {
    var grid = mini.get("datagrid_" + id);
    var arr = grid.getColumns();
    col_index++;

    for(var j=0;j<arr.length;j++) {
        _id_arr.push(arr[j]._id);
    }
    var _id = Math.max.apply(null, _id_arr)+1;//新增的列id取最大值+1,防止_id冲突
    arr.push({
        // field: "datagrid_" + id + '$' + record.id,
        field: record.id,
        header: record.text,
        name: record.id,
        width: 100, headerAlign: "center", allowSort: false,
        editor: { type: "textbox"},
        _id: _id
    });

    grid.setColumns(arr);

    console.log(grid.getColumns());
    var type;
    var tabs_id;
    var tab_id;
    for(var i=0;i<properties.length;i++) {
        if(properties[i].c_id == "datagrid_" + id) {
            type = properties[i].type;
            if(type == 'table') {
                tabs_id = '';
                tab_id = '';
            }else {
                tabs_id = properties[i].tabs_id;
                tab_id = properties[i].tab_id;
            }
        }
    }
    properties.push({
        c_id: "datagrid_" + id,//表格id
        // col_id:  "datagrid_" + id + '$' + record.id,//列id
        col_id:  record.id,//列id
        cLadText: record.text,//字段中文名
        cTableField: record.name,//字段英文名(唯一)
        cTableField_ch: record.text,//字段英文名(唯一)
        cTableFieldType: record.cTableFieldType,//字符类型
        cFormName: '',//表单名
        cLength: '',//自定义长度
        cCombo: '',//自定义下拉框内容
        cCheckbox: '',//自定义复选框内容
        cGridType: 'textbox',//自定义列类型
        cGroup: '',//自定义列分组
        cReference: '',
        cBgReference: '',
        ref: {},
        cMath: '',//公式
        tab_id: tab_id,
        tabs_id: tabs_id,
        cRefObj: {
            cLadText: record.text,
            cTableField: record.id,
            cTableField_ch: record.text
        },
        cTableName: record.tableName,//数据库表名(英文)
        tableClassName: '',//数据库表名(中文)
        iConX: '',
        iConY: '',
        iLabHeight: '',
        iWidth: '',
        iLabWidth: '',
        cEditCss: '',
        lanyoutMent: '',
        type: type
    });
    // grid.on("columnschanged",function (e) {
    //     console.log(e);
    // })

}
//删除指定列
function removeGridCols(id) {
    var grid = mini.get(id.id);
    var arr = grid.getColumns();
    if(arr.length > 1) {
        // var index = arr.indexOf(rightClickCol);
        // arr.splice(index, 1)[0];//删除列数据
        for(var j=0;j<arr.length;j++) {
            if(arr[j].name == rightClickCol.name) {
                arr.splice(j,1)[0];//删除列数据
            }
        }
        console.log(arr);
        grid.set({
            columns: arr
        });

        for(var i=0;i<properties.length;i++) {
            if(properties[i].col_id == rightClickCol.field) {
                properties.splice(i, 1);
            }
        }
        console.log(properties);
        //取消勾选
        var nodes = treeData.getCheckedNodes();
        for(var k=0;k<nodes.length;k++) {
            if(nodes[k].name == rightClickCol.name && nodes[k].tableName == rightClickCol.tableName && nodes[k].ptype == 'child') {
                treeData.uncheckNode(nodes[k]);
            }
        }
    }else {
        removeAllGridCols(id);
    }
}
//删除整表
function removeAllGridCols(id) {
    var grid = mini.get(id.id);
    $(id.id).remove();
    grid.destroy();

    properties = properties.filter(function(x){
        if(id.id == x.c_id){
            //取消勾选
            var nodes = treeData.getCheckedNodes();
            for(var k=0;k<nodes.length;k++) {
                if(nodes[k].name == x.cTableField && nodes[k].tableName == x.cTableName && nodes[k].ptype == 'child') {
                    treeData.uncheckNode(nodes[k]);
                }
            }
            return false
        }
        else{return true}
    });

    console.log(properties);
}
//右键菜单设置列类型
function setGridColEditor(id,type) {
    console.log(id,type);
    console.log(rightClickCol);
    var grid = mini.get("datagrid_" + id);
    var cols = grid.getColumns();

    for(var i=0;i<cols.length;i++) {
        if(cols[i].field == rightClickCol.field) {
            grid.updateColumn(rightClickCol.name, {editor: { type: type}});
        }
    }
    // console.log(grid.getColumns());

    // for(var i=0;i<cols.length;i++) {
    //     if(cols[i].field == rightClickCol.field) {
    //         cols[i].editor = { type: type};
    //     }
    // }
    // grid.set({
    //     columns: cols
    // });
}
/**---------------------------------------操作表格 end----------------------------------------*/


/**---------------------------------------操作tabs start-----------------------------------------*/
//创建页签
// var tabs_index = 0;
function create_tabs(area,edit_data,param,coordinates) {
    // tabs_index++;
    // var id = tabs_index;
    // var thisId = 'tabs_' + id;
    var name = 'tab1';
    var title = 'tab1';

    if(action == 'edit' && editFlag) {
        var thisId = edit_data.data.c_id;//全称
        var id = thisId.substring(thisId.indexOf("_")+1);//数字
        properties[edit_data.i] = edit_data.data;
        properties[edit_data.i].c_id = thisId;
        name = edit_data.data.tab_id;
        title = edit_data.data.cTabText;
        tab_editIndex.push(id);
        tab_index = Math.max.apply(null, tab_editIndex);//最大的值作为新建组件的id起点

    }else {
        tab_index++;
        id = tab_index;//数字
        thisId = 'tab_'+id;//全称
        name = thisId+name;
        properties.push({
            c_id: thisId,//tab id
            tab_id: name,//tab单页id
            cLadText: '',//字段中文名
            cTabText: 'tab1',//字段中文名
            cTableField: '',//字段英文名(唯一)
            cTableField_ch: '',
            cTableFieldType: '',//字符类型
            cFormName: '',//表单名
            cLength: '',//自定义长度
            cCombo: '',//自定义下拉框内容
            cCheckbox: '',//自定义复选框内容
            cGridType: '',//自定义列类型
            cGroup: '',//自定义列分组
            cReference: '',
            cBgReference: '',
            cMath: '',//公式
            cRefObj: {},
            ref: {},//参照总数据
            cTableName: '',//数据库表名(英文)
            tableClassName: '',//数据库表名(中文)
            iConX: '',
            iConY: '',
            iLabHeight: '',
            iWidth: '',
            iLabWidth: '',
            cEditCss: '',
            lanyoutMent: '',
            type: 'tab'
        });
    }

    var $clone = "<div id='" + thisId + "' class='mini-tabs dragbox' activeIndex='0' style='width:350px;height:200px;'\n" +
        "    contextMenu='#tabsMenu" + id + "'>\n" +
        "        <div name='"+name+"' title='"+title+"'> </div>\n" +
        "     </div>";

    var contextMenu = "<ul id='tabsMenu" + id + "' class='mini-contextmenu' onbeforeopen='onBeforeOpenTab(e)'>\n" +
        "    <li onclick='addTab(" + thisId + ")'>新增</li>\n" +
        "    <li onclick='removeTab(" + thisId + ")'>删除</li>\n" +
        "    <li onclick='removeAllTab(" + thisId + ")'>全部删除</li>\n" +
        // "    <li><span >插入</span><ul>" +
        // "       <li onclick='insertTable(" + thisId + ")'>表格</li>\n" +
        // "       <li onclick=\"insertBase(" + thisId + ",'textbox')\">文本框</li>\n" +
        // "       <li onclick=\"insertBase(" + thisId + ",'textarea')\">文本域</li>\n" +
        // "       <li onclick=\"insertBase(" + thisId + ",'formname')\">文本</li>\n" +
        // "       <li onclick=\"insertBase(" + thisId + ",'spinner')\">数值</li>\n" +
        // "       <li onclick=\"insertBase(" + thisId + ",'datepicker')\">时间选择器</li>\n" +
        // "       <li onclick=\"insertBase(" + thisId + ",'buttonedit')\">参照</li>\n" +
        // "       <li onclick=\"insertBase(" + thisId + ",'combobox')\">下拉框</li></ul></li>\n" +
        // // "       <li onclick=\"insertBase(" + thisId + ",'checkbox')\">复选框</li></ul></li>\n" +
        "</ul>";
    if(area == 'mainField') {
        $('#mainField').append($clone);
        $('#mainField').append(contextMenu);
        mini.parse();
        // click_id = thisId;

        if(action == 'edit' && editFlag) {//编辑模式 非拖拽生成的组件

        }else {
            //拖拽位置
            $('#' + thisId).css({
                clear: 'both', left: coordinates.x,
                top: coordinates.y, position: "absolute"
            })
        }
    }
    $("#" + thisId).resizable({
        resize: function () {
            // console.log($("#" + id).height(),'height');

            $("#" + thisId + " .mini-tabs-bodys").css({
                height: $("#" + thisId).height() - 33 - 11,
                width: $("#" + thisId).width() - 12
            });
            $("#" + thisId + " .mini-tabs-scrollCt").css({
                width: $("#" + thisId).width()
            });
            $("#" + thisId + " .mini-tabs-body").css({
                height: '100%'
            });
        }
    });
    $("#" + thisId).draggable({
        // containment: "parent",
        containment: "#mainField",
        scroll: false,
        cursor: "move"
    });
    // $("#" + thisId).click(tabClick);
    // $("#" + thisId).dblclick(tabClick(thisId));
    mini.get(thisId).on("activeChanged",function (e) {
        tabClick(thisId);
    })

    $("#" + thisId).dblclick(function () {
        tabClick(thisId);
    })
    // $("#" + thisId).click(function () {
    //     tabs_id = $(this).attr('id');
    //     console.log(tabs_id,'当前tabs');
    //     var tabs = mini.get(tabs_id);
    //     tabs.activeTab(tabs.getActiveTab());
    // })

}

//tab--点击事件
function tabClick(id) {
    // stopBubbling();
    console.log(properties,'properties');
    // var id = $(this).attr('id');
    var tabs = mini.get(id);

    setTimeout(function () {
        var tab = tabs.getActiveTab();
        console.log(tab,'active tab');

        cancelBlur();
        pre_click_type = click_type;//为空则为第一次点击，不存储
        pre_click_id = click_id;
        // var pre_click_id = click_ids.slice(-2, -1).toString();
        click_type = 'tab';
        click_types.push('tab');
        click_id = tab.name;
        c_id = id;
        click_ids.push(click_id);
        showProperty('tab');

        console.log('--------------------------------');
        console.log('pre:',pre_click_type,',',pre_click_id);
        console.log('now:',click_type,',',click_id);
        savePre(pre_click_type,click_id,pre_click_id);

    },100);
}

//tab右键点击菜单弹出之前
var currentTab = null;//右键操作的菜单
function onBeforeOpenTab(e) {
    var id = e.popupEl.id;
    var tabs = mini.get(id);
    currentTab = tabs.getTabByEvent(e.htmlEvent);
    // tabs.activeTab(currentTab);
    if (!currentTab) {
        e.cancel = true;
    }
}
function addTab(e,param) {

    var tabs = mini.get(e.id);
    if(action == 'edit' && editFlag) {
        var name = param.name;
        var tab_id = name;
        var tab = {title: param.title, name: name};
    }else {
        var name = "tab"+tab_index++;
        var tab_id = e.id+name;
        var tab = {title: name, name: e.id+name};
        properties.push({
            c_id: e.id,//tab id
            tab_id: tab_id,//tab单页id
            cTabText: name,
            cLadText: name,//字段中文名
            cTableField: '',//字段英文名(唯一)
            cTableField_ch: '',
            cTableFieldType: '',//字符类型
            cFormName: '',//表单名
            cLength: '',//自定义长度
            cCombo: '',//自定义下拉框内容
            cCheckbox: '',//自定义复选框内容
            cGridType: '',//自定义列类型
            cGroup: '',//自定义列分组
            cReference: '',
            cBgReference: '',
            cMath: '',//公式
            cRefObj: {},
            ref: {},//参照总数据
            cTableName: '',//数据库表名(英文)
            tableClassName: '',//数据库表名(中文)
            iConX: '',
            iConY: '',
            iLabHeight: '',
            iWidth: '',
            iLabWidth: '',
            cEditCss: '',
            lanyoutMent: '',
            type: 'tab'
        });
    }
    tab = tabs.addTab(tab);
    tabs.activeTab(tab);


    // var el = tabs.getTabBodyEl(tab);
    // el.innerHTML = index;
}
function removeTab(e) {//右键菜单移除
    var tabs = mini.get(e.id);
    // console.log(tabs.getTabs());
    if(tabs.getTabs().length > 1) {
        properties = properties.filter(function(x){//删除数据
            if(currentTab.name == x.tab_id){
                return false
            }
            else{return true}
        })
        console.log(properties,'删除');
        tabs.removeTab(currentTab);
    }else {//最后一个tab
        removeAllTab(e);//删除整个页签
    }
}
function removeAllTab(e) {
    // var tabs = mini.get(id+'');
    // tabs.removeAll();
    $('#'+ e.id).remove();//删除整个页签
    properties = properties.filter(function(x){//删除数据
        if(e.id == x.c_id || e.id == x.tabs_id){
            return false
        }
        else{return true}
    })
}
//插入表格
function insertTable(e,type) {
    var tabs = mini.get(e.id);
    currentTab = tabs.getTab(e.tab_id);
    // console.log(currentTab);
    var tabEl = tabs.getTabBodyEl(currentTab);
    var edit_data = [];
    var edit_id = '';
    var param = {
        area: "div[id='" + tabEl.id + "']",
        c_id: e.id,//整个页签
        tab_id: currentTab.name//插入的当前页签
    }

    if(action == 'edit' && editFlag || type == 'bind') {
        currentTab = tabs.getTab(e.tab_id);
        tabEl = tabs.getTabBodyEl(currentTab);
        edit_data = e.edit_data;
        edit_id = e.edit_id;
        if(type == 'bind') {
            param.type = 'bind'
            //删除原表
            var grid = mini.get('datagrid_' + edit_id);
            $('datagrid_' + edit_id).remove();
            grid.destroy();

            create_table('tabs',edit_data,edit_id,param);

            //更改表格属性为页签表格
            for(var i=0;i<properties.length;i++) {
                if(properties[i].type == 'table') {
                    var id = properties[i].c_id.match(/datagrid_(\S*)/)[1];
                    if(id == e.edit_id) {
                        properties[i].tabs_id = e.id;
                        properties[i].tab_id = e.tab_id;
                        properties[i].type = 'tab_table';
                    }
                }
            }
        }else {
            create_table('tabs',edit_data,edit_id,param);
        }
    }else {
        create_table('tabs',edit_data,edit_id,param);
    }

    console.log(properties,'properties');
}
//插入其他组件
function insertBase(e,type) {
    var tabs = mini.get(e.id);
    // console.log(currentTab);
    var tabEl = tabs.getTabBodyEl(currentTab);
    var edit_data = [];

    if(action == 'edit' && editFlag) {
        currentTab = tabs.getTab(e.tab_id);
        tabEl = tabs.getTabBodyEl(currentTab);
        edit_data = e.edit_data;
    }
    var param = {
        area: "div[id='" + tabEl.id + "']",
        c_id: e.id,//整个页签
        tab_id: currentTab.name//插入的当前页签
    }
    if(type == 'textbox') {
        create_textbox('tabs',edit_data, param);
    }else if(type == 'textarea') {
        create_textarea('tabs',edit_data, param);
    }else if(type == 'formname') {
        create_formname('tabs',edit_data, param);
    }else if(type == 'spinner') {
        create_spinner('tabs',edit_data, param);
    }else if(type == 'buttonedit') {
        create_buttonedit('tabs',edit_data, param);
    }else if(type == 'datepicker') {
        create_datepicker('tabs',edit_data, param);
    }else if(type == 'combobox') {
        create_combobox('tabs',edit_data, param);
    }else if(type == 'checkbox') {
        create_checkbox('tabs',edit_data, param);
    }
}

/**---------------------------------------操作页签 end------------------------------------------*/


/**----------------------------------------公共函数 start------------------------------------*/

//多个点击事件冲突处理
function stopBubbling(e,type) {
    e = window.event || e;
    if (e.stopPropagation) {
        if(type == 'table') {
            // e.stopPropagation();
        }else {
            // return false;
        }
        // e.stopPropagation();      //阻止冒泡但是允许默认事件的发生
        // e.preventDefault();       //阻止默认事件但是允许冒泡事件的发生
        return false                 //阻止默认事件和冒泡事件
    } else {
        e.cancelBubble = true;   //ie兼容
    }
}

//基础组件缩放
function resize_base(id) {
    var $item = $("#" + id);
    // var num = id.substring(id.indexOf("_")+1);//截取数字部分
    $item.resizable({
        handles: 'n, e, s, w, ne, se, sw, nw',
        grid: [2, 2],
        resize: function () {
            // console.log($(this),'--');

            $('#left' + id).css({
                'line-height': $('#left' + id).height()
            });
            $('#left' + id + ' p.text').css({
                'margin-top': ($('#left' + id).height() - $('#left' + id + ' p.text').height())/2
            });
            // console.log($(this).width() - $('#left' + id).width() - 8);
            console.log($('#'+id).height())

            $('#right' + id).css({
                width: $(this).width() - $('#left' + id).width() - 3,
                height: $('#'+id).height()
            })
            if(id.indexOf('formname_'>-1)) {
                $('#right' + id + ' p.text').css({
                    'margin-top': ($('#right' + id).height() - $('#right' + id + ' p.text').height())/2
                });
            }
        }
    });
    var clickX, leftOffset;
    var dragging = false;
    var labBtn = $('#lab' + id);
    //中间线调整尺寸
    labBtn.bind('mousedown', function (e) {
        dragging = true;
        // console.log($(this).attr('id'));
        leftOffset = $('#' + id).offset().left;//左坐标
        $('#' + id).draggable('disable');
        //按下并拖动鼠标
        $('#' + id).bind('mousemove', function (e) {
            clickX = e.pageX;
            console.log(e.pageX);
            $('#left' + id).css('width', clickX - 7 - leftOffset + 'px');
            $('#lab' + id).css('left', clickX - 7 - leftOffset + 'px');
            $('#right' + id).css('left', clickX - 4 - leftOffset + 'px');
            $('#right' + id).css('width', $(this).width() - clickX + 4 + leftOffset + 'px');
        })
        e.stopPropagation();
    });

    $item.mouseup(function (e) {
        $('#' + $(this).attr('id')).unbind('mousemove');
        $('#' + $(this).attr('id')).draggable('enable');
        dragging = false;
    })
    // $item.css("position", "absolute");
    $item.draggable({
        grid: [2, 2],
        containment: "parent",
        cursor: "move",
        snap: true,
        snapTolerance: 20,
        start: function (e) {

        },
        stop: function (e) {

        }
    });

}
//miniui组件修改文字
function setBoxText(id,value) {
    var box = mini.get(id);
    box.setText(value);
}
//删除组件
function removeBox(e) {
    $("#" + e.id).remove();//删除组件
    //删除数据
    var delItem;
    properties = properties.filter(function(x){
        if(e.id == x.c_id){
            // if(formTypes == "complex" && x.type.indexOf('buttonedit')>-1) {//删除档案的数据
            //     cTreeData.selected.filter(function(y){
            //         if(y.cTableField == x.cTableField) {
            //             return false
            //         }else{
            //             return true
            //         }
            //     })
            // }
            delItem = x;
            return false
        }
        else{return true}
    })
    console.log('已删除',properties);
    //取消勾选
    var nodes = treeData.getCheckedNodes();
    for(var i=0;i<nodes.length;i++) {
        if(nodes[i].name == delItem.cTableField && nodes[i].ptype == 'main') {
            treeData.uncheckNode(nodes[i]);
        }
    }

}

//点击组件
function baseClick(e,type,id,cTableFieldType) {
    stopBubbling(e);//多个点击事件冲突处理
    cancelBlur();
    pre_click_type = click_type;//为空则为第一次点击，不存储
    pre_click_id = click_id;
    // var pre_click_id = click_ids.slice(-2, -1).toString();
    click_type = type;
    click_types.push(type);
    click_id = id;
    click_ids.push(click_id);

    showProperty(type.substring(type.indexOf('_')+1));
    setCompOption(cTableFieldType);

    console.log('--------------------------------');
    console.log('pre:',pre_click_type,',',pre_click_id);
    console.log('now:',click_type,',',click_id);
    savePre(pre_click_type,click_id,pre_click_id);
}

function savePre(pre_type,click_id,pre_id) {

    console.log('properties',properties);

    var param;
    var pre_param;
    if(click_type == 'table' || click_type == 'tab_table') {
        param = 'col_id';
    }else if(click_type == 'tab') {
        param = 'tab_id';
    }else {
        param = 'c_id';
    }
    if(pre_type == 'table' || click_type == 'tab_table') {
        // param = 'cTableField';
        pre_param = 'col_id';
    }else if(pre_type == 'tab') {
        pre_param = 'tab_id';
    }else {
        pre_param = 'c_id';
    }

    // if(gridClick_num > 0 && param == 'col_id') {
    for(var i=0;i<properties.length;i++) {
        if(pre_id == properties[i][pre_param]) {
            if(pre_type == 'tab' && properties[i].type != 'tab') {
                continue;
            }
            // properties[i].cTableField = cTableField.getText();//弹窗
            properties[i].cTableField = cTableField.getValue();//文本
            properties[i].cTableField_ch = cTableField_ch.getValue();//文本
            properties[i].cLadText = cLadText.getValue();//文本
            properties[i].cTabText = cTabText.getValue();//页签名
            properties[i].cFormTitle = cFormTitle.getValue();//文本
            properties[i].cComType = cComType.getValue();//下拉
            properties[i].cFontSize = cFontSize.getValue();//下拉
            properties[i].cLength = cLength.getValue();//文本
            properties[i].cFormat = cFormat.getValue();//下拉
            properties[i].cDateDefault = cDateDefault.getValue();//下拉
            properties[i].cReference = cReference.getValue();//弹窗
            // properties[i].cBgReference = cBgReference.getValue();//弹窗
            properties[i].cCombo = cCombo.getValue();//文本域
            properties[i].cCheckbox = cCheckbox.getValue();//文本域
            properties[i].cGridType = cGridType.getValue();//下拉
            properties[i].cGroup = cGroup.getValue();//文本框

            properties[i].cRefObj.display = disable.getValue()

            properties[i].cRequire = cRequire.getValue();//下拉
            properties[i].cNull = cNull.getValue();//下拉
            properties[i].cSpinner = cSpinner.getValue();//文本
            // properties[i].cTree = cTree.getValue();//参照档案

            properties[i].cRefObj = getForm();
        }
    }
    console.log('已存储pre',properties);
    // }


    //更新属性
    for(var i=0;i<properties.length;i++){

        if(click_id == properties[i][param]) {

            if(click_type == 'tab' && properties[i].type != 'tab') {
                continue;
            }
            var cRef = properties[i].cRefObj;
            console.log(cRef,'需要显示的属性');
            resetForm();
            if(typeof cRef == 'string') {
                cRef = $.parseJSON(cRef)
            }
            setForm(cRef);
            cTabText.setValue(cRef.cTabText);
            cFormTitle.setValue(cRef.cFormTitle);
            cMath.setText(properties[i].cMath.value);

            if(click_type == 'table' || click_type == 'tab_table') {
                //若点击的表格列,动态属性框
                setGridProperty(cGridType.getValue());
            }
        }
    }
    // cLadText.doValueChanged();

}
//表单操作
function getForm() {
    var form = new mini.Form("#form1");
    var data = form.getData();
    // var s = mini.encode(data);
    return data;
}
function setForm(obj) {
    var form = new mini.Form("#form1");
    // if(obj) {
    //     obj.cType = switchRef(obj.cType);
    // }
    form.setData(obj, false);
    // cTableField.setText(obj.cTableField);
}
function resetForm() {
    var form = new mini.Form("#form1");
    form.reset();
}
function clearForm() {
    var form = new mini.Form("#form1");
    form.clear();
}

var key = '';
var key_id = '';
if(action == 'edit') {
    for(var i=0;i<edit_data.length;i++) {
        if(edit_data[i].type != 'table' && edit_data[i].type != 'tab_table' && edit_data[i].type != 'tab'){
            key = edit_data[i].cTableName;//主表名
            key_id = edit_data[i].tableClassId;//主表id
            break;
        }
    }

}
//绑定数据库表字段
function onBindKey() {
    var keySelected = [];//所有组件的字段英文名，用于判断绑定字段的唯一
    var keyList_main = [];//主表选择的表
    var keyList_child = [];//子表选择的表
    for(var i=0;i<properties.length;i++) {
        keySelected.push({
            cTableField:properties[i].cTableField,//字段
            cTableName:properties[i].cTableName//所属表
        });
        if(properties[i].type !='tab' && properties[i].type !='table' && properties[i].type !='tab_table') {
            keyList_main.push(properties[i].cTableName);
        }else if(properties[i].type =='table' || properties[i].type =='tab_table') {
            keyList_child.push(properties[i].cTableName);
        }
    }
    mini.open({
        url : bootPATH + "../frame/frame1/pages/formDesign/bindKey.html",
        title : "绑定字段",
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = {
                click_type: click_type,
                key: key,
                key_id: key_id,
                selected: keySelected,
                keyList_main: keyList_main,
                keyList_child: keyList_child
            };
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'bindKey');
                var param;
                if(click_type == 'table' || click_type == 'tab_table') {
                    param = 'col_id';
                }else {
                    key = data.tableClassName;
                    key_id = data.PID;
                    param = 'c_id';
                }
                console.log(key_id,'key_id');
                cTableField.setValue(data.field);
                cTableField.setText(data.field);
                cLadText.setValue(data.fieldCh);
                cLadText.doValueChanged();//主动激发valuechanged事件



                for(var i=0;i<properties.length;i++) {
                    if(properties[i][param] == click_id) {
                        properties[i].cTableName = data.tableClassName;//数据库表名(英文)
                        properties[i].tableClassName = data.cTableName;//数据库表名(中文)
                        properties[i].tableClassId = data.PID;//数据库表id
                    }
                }
            }
        }
    })
}

//绑定数据库表字段
function onSetMath() {
    // 存放被点击的组件信息
    var db = [];
    // 存放历史公式
    var pre;
    // 用来获取被点击元素数据的参数(判断)
    var param;
    // 根据被点击元素的类型定义获取数据的属性
    if(click_type == 'table' || click_type == 'tab_table') {
        // param = 'cTableField';
        param = 'col_id';
    }else if(click_type.indexOf('tab_')>-1 && click_type != 'tab_table') {
        param = 'c_id';
    }else {
        param = 'c_id';
    }
    // 获取被点击元素属性
    for(var i=0;i<properties.length;i++) {
        if(properties[i][param] == click_id) {
            db = properties[i];//点击的组件信息
            pre = properties[i].cMath;//历史公式数据
        }
    }
    // 打开公式配置页面
    mini.open({
        url : bootPATH + "../frame/frame1/pages/formDesign/setMath.html",
        title : "公式",
        style : "width:900px;height:500px;",
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = { pre: pre, db: db };
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'onSetMath');
                // 公式元素赋值
                cMath.setText(data.value);
                cMath.setValue(data.value);

                // var param;
                // if(click_type == 'table' || click_type == 'tab_table') {
                //     // param = 'cTableField';
                //     param = 'col_id';
                // }else {
                //     param = 'c_id';
                // }
                for(var i=0;i<properties.length;i++) {
                    if(properties[i][param] == click_id) {
                        // properties[i].cMath = data.value;
                        properties[i].cMath = data;
                    }
                }
            }
        }
    })
}

//表单取消焦点，避免input值丢失问题
function cancelBlur() {
    // mini.get("cTableField").blur();
    mini.get("cLadText").blur();
    mini.get("cTabText").blur();
    mini.get("cFormTitle").blur();
    mini.get("cLength").blur();
    mini.get("cReference").blur();
    // mini.get("cBgReference").blur();
    mini.get("cCombo").blur();
    mini.get("cCheckbox").blur();
}


//表单名唯一校验
cFormName.on("blur", function (e) {
    var menuName =  cFormName.getValue();
    if(menuName) {
        $.ajax({
            url: ajaxUrl + "/menus/findMenuName.do",
            type: "post",
            dataType: "json",
            traditional: true,
            data: {
                menuName: menuName
            },
            success: function(data){
                console.log(data,'表单名唯一');
                if(data.state == 'error'){
                    mini.alert('表单名称重复！');
                    cFormName.setValue('');
                }
            },
            error : function(data){
            }
        });
    }
})

//更改字段中文名
cLadText.on("valuechanged", function (e) {
    // console.log(e.value);
    // console.log(click_id,'click_id');
    var param = 'c_id';
//    if(click_type == 'checkbox') {
//        setBoxText(click_id.replace('box',''),e.value);
//
//    }else
    if(click_type == 'table' || click_type == 'tab_table') {
        param = 'col_id';
        var grid = mini.get(c_id);
        // var update_name = click_id.match(/\$(\S*)/)[1]
        var update_name = click_id;

        grid.updateColumn(update_name, {
            // field: cTableField.getText(),
            header: e.value,
            // name: cTableField.getText()
        });

    }else if(click_type == 'tab') {
        // param = 'tab_id';
        // //更新页签title
        // var tabs = mini.get(c_id);
        // var tab = tabs.getTab(click_id);
        // tabs.updateTab(tab, {title: e.value});

    }else {
        // $('#'+click_id+' .left p.text').html('');
        $('#'+click_id+' .left p.text').html(e.value);
    }

    if(click_type == 'tab') {

    }else {
        for(var i=0;i<properties.length;i++) {
            if(properties[i][param] == click_id) {
                // properties[i].cTableField = cTableField.getText();
                properties[i].cLadText = cLadText.getValue();
                properties[i].cRefObj = getForm();
            }
        }
    }

    console.log('----pre:',pre_click_type,',',pre_click_id);
    console.log('----now:',click_type,',',click_id);
});
//更改页签名
cTabText.on("valuechanged", function (e) {
    param = 'tab_id';
    //更新页签title
    var tabs = mini.get(c_id);
    var tab = tabs.getTab(click_id);
    tabs.updateTab(tab, {title: e.value});

    console.log('----pre:',pre_click_type,',',pre_click_id);
    console.log('----now:',click_type,',',click_id);
});

//更改文本
cFormTitle.on("valuechanged", function (e) {
    $("#right"+click_id +" .text").html(e.value);
});

//更改组件类型
cComType.on("valuechanged", function (e) {
    console.log(e.value);
    console.log(click_id,'当前组件');

    //存储当前组件位置参数
    var ix;
    var iy;
    var type;
    var del_id = click_id;
    var mainField = $("#mainField").children();
    console.log(mainField,'mainField');
    for(var i=0;i<mainField.length; i++){
        if(mainField[i].id == del_id) {
            ix = mainField[i].offsetLeft;
            iy = mainField[i].offsetTop;
            type = mainField[i].type;
        }
    }
    var record;
    for(var j=0;j<properties.length; j++){
        if(properties[j].c_id == del_id) {
            record = properties[j];
        }
    }

//    removeBox({id: click_id});//删除原组件

    create(e.value,'',{x:ix,y:iy,type:'compChanged'},
        {
            name: cTableField.getValue(), name_ch: cTableField_ch.getValue(),
            text: cLadText.getValue(),
            cTableFieldType: record.cTableFieldType, tableName: record.cTableName
        });
    $("#" + del_id).remove();//删除组件
    //删除数据
    var delItem;
    properties = properties.filter(function(x){
        if(del_id == x.c_id && type != x.type){
            delItem = x;
            return false
        }
        else{return true}
    })
    console.log(properties,'组件更新');

    var records = treeData.getList();
    // for(var p=0;p<records.length;p++) {
    //     if(records[p].ptype == 'main' && records[p].mTableId == undefined) {//主表字段
    //         if(records[p].name == cTableField.getValue()) {
    //             treeData.checkNode(records[p]);
    //         }
    //     }
    // };
    showProperty(e.value.substring(e.value.indexOf('_')+1));
});

//更改文本字号
cFontSize.on("valuechanged", function (e) {
    if(click_type.indexOf('formname')>-1) {
        $("#right"+click_id +" .text").css({
            "font-size": e.value+'px'
        });
    }else if(click_type.indexOf('table')>-1) {

    }else if(click_type.indexOf('tab')>-1) {
//    	$(".mini-tab-text").css({
//            "font-size": e.value+'px'
//        });

    }else if(click_type.indexOf('textarea')>-1) {
        $(".box #left"+click_id).css({
            "font-size": e.value+'px'
        });
        $(".box #right"+click_id+" textarea").css({
            "font-size": e.value+'px'
        });
    }else {
        // var id = click_type.substring(click_type.indexOf("_")+1);
        // $(".box-"+id).css({
        //     "font-size": e.value+'px'
        // });
        $(".box #left"+click_id).css({
            "font-size": e.value+'px'
        });
        $(".box #right"+click_id+" input").css({
            "font-size": e.value+'px'
        });
    }

});

//设计模式变化
function onDesignModeChanged(e) {
    designMode = e.value;
    if(designMode == 'complex') {
        $("#cTree").css({
            display: "inline-block"
        })
    }else {
        // $("#cTree").css({
        //     display: "none"
        // })
    }
}

//布局方式变化
function onLayoutTypeChanged(e) {

}

//一键布局
function setLayout(e) {
    var value = mini.get("cLayoutType").getValue();
    console.log(value);

}

//复杂档案 关联
function onSetTree(e) {
    var refData = [];//参照数据
    for(var i=0;i<properties.length;i++) {
        if(properties[i].ref != undefined && properties[i].ref.ref != undefined) {
            refData.push(properties[i].ref.ref);
        }
    }
    console.log(refData,'refData');

    mini.open({
        url : bootPATH + "../frame/frame1/pages/formDesign/selectFile.html",
        title : "树形设置",
        width: 600,
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = {action: action, refData: refData,
                selected: cTreeData.selecteds,treeList:cTreeData.treeList};
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {       //如果点击“确定”
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'----');
                cTreeData = data;
                cTreeStruct = "";
                for(var i=0;i<cTreeData.treeList.length;i++) {
                    var item = cTreeData.treeList[i];
                    cTreeStruct += item.cTableName + ","
                }
                cTreeStruct=cTreeStruct.substring(0,cTreeStruct.length-1);
            }
        }
    })
}

//表头分组
function oncGroupChanged(e) {
    console.log(e.value);

    // var grid_id = click_id.match(/(\S*)\$/)[1];//截取
    // var grid_id = click_id.match(/(\S*)_xgry/)[1];//截取
    var grid_id = grid_message.column.tableName;
    var grid = mini.get('datagrid_'+grid_id);
    var cols = grid.getColumns();//所有列
    var curCol = grid.getColumn(click_id);//当前列

    mini.open({
        url : bootPATH + "../frame/frame1/pages/formDesign/setGridGroup.html",
        title : "选择表格列分组",
        width: 500,
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = {grid_id: grid_id, properties: properties, cols: cols};
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {       //如果点击“确定”
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'----');
                grid.set({
                    columns: data
                })

            }
        }
    })
}

//表格列类型属性
function oncGridTypeChanged(e) {
    console.log(e.value);
    var grid_id = gridClick_id;
    if(click_id.indexOf('_xgry') > -1) {
        // var grid_id = click_id.match(/(\S*)\$/)[1];//截取
        // grid_id = click_id.match(/(\S*)_xgry/)[1];//截取
        var grid_id = grid_message.column.tableName;
    }

    var grid = mini.get('datagrid_'+grid_id);
    var cols = grid.getColumns();

    //更新表格列样式
    for(var i=0;i<cols.length;i++) {
        if(cols[i].field == click_id) {
            grid.updateColumn(cols[i].name, {editor: { type: e.value}});
        }
    }
    setGridProperty(e.value);
}
//下拉框内容属性
function onComboChanged(e) {
    console.log(e.value);
    var combo_arr = e.value.split(/[(\r\n)\r\n]+/);
    console.log(combo_arr);

    var combo_data = [];
    for(var i=0;i<combo_arr.length;i++) {
        combo_data.push({
            'id':combo_arr[i],'text':combo_arr[i]
        })
    }


    if(click_type == 'table' || click_type == 'tab_table') {
        //表格设置下拉框
        // var grid_id = click_id.match(/(\S*)\$/)[1];//截取
        // var grid_id = click_id.match(/(\S*)_xgry/)[1];//截取
        var grid_id = grid_message.column.tableName;
        var grid = mini.get('datagrid_'+grid_id);
        var cols = grid.getColumns();
        for(var i=0;i<cols.length;i++) {
            if(cols[i].field == click_id) {
                grid.updateColumn(cols[i].name, {editor: { type:'combobox', data: combo_data}});
            }
        }
        // mini.get(c_id).updateColumn(click_id, {editor: { type:'combobox', data: combo_data}})
    }else {
        var id = click_id.replace("combobox_","combo");
        var combo = mini.get(id);
        combo.setData(combo_data);
    }
}
//复选框内容属性
function onCheckboxChanged(e) {
    console.log(e.value);
    var check_arr = e.value.split(/[(\r\n)\r\n]+/);
    console.log(check_arr);

    var check_data = [];
    for(var i=0;i<check_arr.length;i++) {
        var item = check_arr[i].split(',');
        check_data.push({
            'id':item[0],'text':item[1]
        })
    }
    var id = click_id.replace("checkbox_","check");
    var check = mini.get(id);
    check.setData(check_data);
    // mini.get('check'+id).setData([
    //     { "id": "int", "text": "整数类型" },
    //     { "id": "nvarchar(max)", "text": "字符串类型" },
    //     { "id": "datetime", "text": "时间类型" },
    //     { "id": "numeric", "text": "小数类型" },
    // ]);
}

//主表 属性栏 动态
function showProperty(type) {

    if(type == 'textbox' || type == 'textarea') {
        $(".cLadText").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cFontSize").css({
            display: "table-row"
        })
        $(".cRequire").css({
            display: "table-row"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cLength").css({
            display: "table-row"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "table-row"
        })
        $(".cCannotbezero").css({
            display: "table-row"
        })
    }else if(type == 'fileupload') {
        $(".cLadText").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cFontSize").css({
            display: "none"
        })
        $(".cRequire").css({
            display: "table-row"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "table-row"
        })
        $(".cCannotbezero").css({
            display: "none"
        })
    }else if(type == 'buttonedit') {

        // if(designMode == 'complex') {//复杂档案
        //     $(".cTree").css({
        //         display: "table-row"
        //     })
        // }else {//表单或简单档案
        //     $(".cTree").css({
        //         display: "none"
        //     })
        // }
        $(".cTableField").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cLadText").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cFontSize").css({
            display: "table-row"
        })
        $(".cRequire").css({
            display: "table-row"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cReference").css({
            display: "table-row"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "table-row"
        })
    }else if(type == 'combobox') {
        $(".cFontSize").css({
            display: "table-row"
        })
        $(".cLadText").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cRequire").css({
            display: "table-row"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cCombo").css({
            display: "table-row"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "table-row"
        })
    }else if(type == 'datepicker') {
        $(".cFontSize").css({
            display: "table-row"
        })
        $(".cLadText").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cRequire").css({
            display: "table-row"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cFormat").css({
            display: "table-row"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "table-row"
        })

        dateFormat();

    }else if(type == 'table') {
        $(".cFontSize").css({
            display: "none"
        })
        $(".cLadText").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cRequire").css({
            display: "table-row"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cGridType").css({
            display: "table-row"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cMath").css({
            display: "table-row"
        })
        cGridType.setData([{
            'id':'textbox','text':'文本'
        },{
            'id':'textarea','text':'文本域'
        },{
            'id':'datepicker','text':'时间'
        },{
            'id':'combobox','text':'下拉框'
        },{
            'id':'buttonedit','text':'参照'
        }]);
    }else if(type == 'tab') {
        $(".cFontSize").css({
            display: "none"
        })
        $(".cLadText").css({
            display: "none"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cRequire").css({
            display: "none"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "table-row"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "none"
        })
        $(".cTableField_ch").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "none"
        })
        $(".cComType").css({
            display: "none"
        })
        // $(".cTree").css({
        //     display: "none"
        // })
    }else if(type == 'formname') {
        $(".cFontSize").css({
            display: "table-row"
        })
        $(".cLadText").css({
            display: "none"
        })
        $(".cComType").css({
            display: "none"
        })
        $(".cRequire").css({
            display: "none"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "table-row"
        })
        $(".cTableField").css({
            display: "none"
        })
        $(".cTableField_ch").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "none"
        })
        // $(".cTree").css({
        //     display: "none"
        // })
    }else if(type == 'checkbox') {
        $(".cFontSize").css({
            display: "table-row"
        })
        $(".cLadText").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cRequire").css({
            display: "none"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cCheckbox").css({
            display: "table-row"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "none"
        })
    } else if(type == 'spinner') {
        $(".cFontSize").css({
            display: "table-row"
        })
        $(".cLadText").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "table-row"
        })
        $(".cRequire").css({
            display: "table-row"
        })
        $(".cSpinner").css({
            display: "table-row"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "table-row"
        })
        $(".cTableField_ch").css({
            display: "table-row"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cMath").css({
            display: "table-row"
        })
    } else {
        $(".cFontSize").css({
            display: "none"
        })
        $(".cLadText").css({
            display: "none"
        })
        $(".cComType").css({
            display: "none"
        })
        $(".cRequire").css({
            display: "none"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cFormTitle").css({
            display: "none"
        })
        $(".cTabText").css({
            display: "none"
        })
        $(".cTableField").css({
            display: "none"
        })
        $(".cTableField_ch").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
        $(".cCheckbox").css({
            display: "none"
        })
        $(".cGridType").css({
            display: "none"
        })
        $(".cSpinner").css({
            display: "none"
        })
        $(".cMath").css({
            display: "none"
        })
    }
}
//表格 属性栏 动态
function setGridProperty(type) {
    if(type == 'buttonedit') {

        // if(designMode == 'complex') {//复杂档案
        //     $(".cTree").css({
        //         display: "table-row"
        //     })
        // }else {//表单或简单档案
        //     $(".cTree").css({
        //         display: "none"
        //     })
        // }
        $(".cReference").css({
            display: "table-row"
        })

        $(".cComType").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
    }else if(type == 'datepicker') {
        $(".cFormat").css({
            display: "table-row"
        })
        dateFormat();
        $(".cComType").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
    }else if(type == 'combobox') {
        $(".cCombo").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
    }else if(type == 'textbox' || type == 'textarea') {
        $(".cLength").css({
            display: "table-row"
        })
        $(".cComType").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
    }else {
        $(".cComType").css({
            display: "none"
        })
        $(".cLength").css({
            display: "none"
        })
        $(".cReference").css({
            display: "none"
        })
        $(".cFormat").css({
            display: "none"
        })
        $(".cCombo").css({
            display: "none"
        })
    }
}

// 设置时间格式化类型
function dateFormat() {
    cFormat.setData([{
        'id':'yyyy-MM-dd','text':'yyyy-MM-dd'
    },{
        'id':'yyyy/MM/dd','text':'yyyy/MM/dd'
    }]);
    cDateDefault.setData([{
        'id':'true','text':'是'
    },{
        'id':'false','text':'否'
    }]);
}
//编辑模式时设置组件名称
function setEditBoxText(type,id) {
    var boxText = '';
    if(action == 'edit' && editFlag) {

        if(type == 'table') {

        }else if(type == 'tab'){

        }else {
            for(var i=0;i<properties.length;i++) {
                if(id == properties[i].c_id) {

                    if(type == 'formname') {
                        boxText = properties[i].cFormTitle;
                    }else {
                        boxText = properties[i].cLadText;
                    }
                }
            }
            // if(type == 'checkbox') {
            //     setBoxText(id.replace('box',''), boxText);
            // }else
            if(type == 'formname'){
                // setBoxText('right'+id, boxText);
                $('#right'+id).html(boxText);
            }else {
                $('#'+id+' .left p.text').html(boxText);
            }
        }
    }

}
//表单验证
function formValid() {
    var form1 = new mini.Form("#cFormName");
    form1.validate();
    if (form1.isValid() == false) {
        alert('表单名称不能为空');
        return;
    }
    if(!parId) {//菜单是否选中验证
        mini.alert('请选择菜单');
        return;
    }
    if(buttons == '') {//菜单是否选中验证
        mini.alert('请选择按钮');
        return;
    }
}
//保存
function save() {
    console.log(cTreeData,'保存的时候获取到的数据+++++++++++++++++++++++++++++');
    savePre(click_type,click_id,click_id);//保存最后的数据
    console.log('properties',properties);


    //存储位置参数
    var mainField = $("#mainField").children();
    console.log(mainField,'mainField');
    for(var i=0;i<mainField.length; i++){
        for(var j=0;j<properties.length;j++) {
            var c_id = properties[j].c_id;
            if(mainField[i].id == c_id) {
                properties[j].cFormName = cFormName.getValue();
                properties[j].formTypes = designMode;
                properties[j].modelId = modelId;
                properties[j].cLayoutType = cLayoutType.getValue();
                properties[j].cDataTree = JSON.stringify(treeData.getData                                           ());//数据树形
                properties[j].cTree = JSON.stringify(cTreeData);

                if(cTreeStruct) {
                    properties[j].cTreeStruct = cTreeStruct;
                }else {
                    properties[j].cTreeStruct = properties[j].cTreeStruct;
                }




                properties[j].iConX = mainField[i].offsetLeft;
                properties[j].iConY = mainField[i].offsetTop;
                properties[j].cEditCss = mainField[i].className;
                properties[j].iLabHeight = mainField[i].offsetHeight;
                properties[j].iWidth = mainField[i].offsetWidth;//总宽度


                if(properties[j].cMath) {
                    properties[j].cMath = properties[j].cMath;
                }else if(properties[j].cMath == "") {
                    properties[j].cMath = "";
                }else {
                    properties[j].cMath = JSON.stringify(properties[j].cMath);
                }
                properties[j].parId = modularId;
                properties[j].modularId = parId;
                properties[j].modular = modular;
                properties[j].buttons = buttons;
                if(properties[j].type == 'table') {
                    properties[j].iLabWidth = properties[j].iWidth;
                    var cols = CircularJSON.stringify(mini.get(properties[j].c_id).getColumns());
                    properties[j].gridColumns = cols;
                    properties[j].lanyoutMent = '2';
                }else if(properties[j].type == 'tab') {
                    properties[j].iLabWidth = properties[j].iWidth;
                }else{
                    properties[j].iLabWidth = mainField[i].children[2].offsetWidth;//右侧宽度
                    properties[j].lanyoutMent = '1';
                }
            }
        }
    }
    //保存页签插入的组件的数据
    for(var m=0;m<properties.length;m++) {
        var c_id = properties[m].c_id;
        var tabs_id = properties[m].tabs_id;
        var tab_id = properties[m].tab_id;
        if(properties[m].type.indexOf('tab_')>-1) {//页签插入的组件
            var field = mini.get(tabs_id).getTabBodyEl(tab_id).children;
            console.log(field);
            for(var p=0;p<field.length;p++) {
                if(field[p].id == c_id) {
                    mini.get(tabs_id).activeTab(tab_id);//激活每个页签以保存数据
                    properties[m].cFormName = cFormName.getValue();
                    properties[m].formTypes = designMode;
                    properties[m].modelId = modelId;
                    properties[m].cLayoutType = cLayoutType.getValue();
                    properties[m].cDataTree = JSON.stringify(treeData.getData());//数据树形
                    properties[m].cTree = JSON.stringify(cTreeData);
                    properties[m].cTreeStruct = cTreeStruct;
                    properties[m].iConX = field[p].offsetLeft;
                    properties[m].iConY = field[p].offsetTop;
                    properties[m].cEditCss = field[p].className;
                    properties[m].iLabHeight = field[p].offsetHeight;
                    properties[m].iWidth = field[p].offsetWidth;//总宽度
                    // if(properties[m].cMath == "") {
                    //     properties[m].cMath = "";
                    // }else {
                    //     properties[m].cMath = JSON.stringify(properties[m].cMath);
                    // }

                    if(properties[m].cMath) {
                        properties[m].cMath = properties[m].cMath;
                    }else if(properties[m].cMath == "") {
                        properties[m].cMath = "";
                    }else {
                        properties[m].cMath = JSON.stringify(properties[m].cMath);
                    }
                    properties[m].parId = modularId;
                    properties[m].modularId= parId;
                    properties[m].modular= modular;
                    properties[m].buttons= buttons;
                    if(properties[m].type == 'tab_table') {
                        var cols = CircularJSON.stringify(mini.get(properties[m].c_id).getColumns());
                        properties[m].gridColumns = cols;
                        properties[m].iLabWidth = properties[m].iWidth;
                        properties[m].lanyoutMent = '2';
                    }else {
                        properties[m].iLabWidth = field[p].children[2].offsetWidth;//右侧宽度
                        properties[m].lanyoutMent = '1';
                    }
                }
            }
        }
    }
    console.log(properties,'已保存');
    console.log(JSON.stringify(properties));

    // formValid();
    // 表单验证
    var form1 = new mini.Form("#cFormName");
    form1.validate();
    if (form1.isValid() == false) {
        mini.alert('表单名称不能为空');
        return;
    }
    if(parId == undefined) {//菜单是否选中验证
        mini.alert('请选择菜单');
        return;
    }
    //传数据
    var url;

    if(action == 'edit') {
        url =  ajaxUrl + "/formltems/updateForm.do";
//        url =  "http://192.168.31.65:8080/bpm/formltems/updateForm.do";
    }else {
        if(openId == undefined || openId == '' || openId == "") {//add下第一次保存
            url =  ajaxUrl + "/formltems/insertForm.do";
//        	url =  "http://192.168.31.65:8080/bpm/formltems/insertForm.do";
            openId = new Date().getTime();
        }else {//edit
            url =  ajaxUrl + "/formltems/updateForm.do";
//            url =  "http://192.168.31.65:8080/bpm/formltems/updateForm.do";
        }
    }
//    url =  "http://192.168.31.65:8080/bpm/formltems/insertForm.do";
    for(var q=0;q<properties.length;q++) {
        properties[q].openId = openId;
    }
    //加字段(referenceField)
    var obj = [];
    if(properties.length > 0){
        properties.forEach(function(item,index){
            item.referenceField = JSON.parse(item.cTree);
            if(item.referenceField != ""){
                item.referenceField = item.referenceField.selecteds;
                obj = item.referenceField;
                var arr = [];
                obj.forEach(function(item1,index){
                    arr.push(item1.cTableField)
                });
                item.referenceField = arr.join();
            }
        });
    }

    console.log(properties,'最后保存转换字符串之前的数据');

    $.ajax({
        type : 'POST',
        url : url,
        dataType : 'json',
        contentType: "application/json",
        data : JSON.stringify(properties),
        success: function (data) {
            mini.alert('保存成功！');
            // parent.removeTab();//保存成功，关闭页面
            saveBtn=mini.get("saveBtn");
            saveBtn.disable();
            modify=mini.get("modify");
            modify.enable();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('保存失败！');
            // console.log(jqXHR);
        }
    })
}

// move(textbox,mainField,'textbox');
//
// function move(ele, box, type) {
//     // box.ondragover = function (target) {
//     //     target.preventDefault(); //默认是不接受被拖拽元素的,所以要禁用默认事件
//     // }
//     // ele.onmousedown = function () {//按下组件
//     //     // box.ondrop = function () {//面板松开鼠标
//     //     //     // console.log(dragType,'拖动类型')
//     //     //     create(type);
//     //     // }
//     // }
//
//     ele.onmousedown = function () {//选中组件并移动
//         console.log('移动元素');
//         // 当被拖拽的元素经过时触发
//         box.ondragover = function (target) {
//             target.preventDefault(); //默认是不接受被拖拽元素的,所以要禁用默认事件
//         }
//
//         box.ondrop = function () {//面板松开鼠标
//             // console.log(dragType,'拖动类型')
//             create(type);
//         }
//     }
// }

//对齐方式
function Alignment(value) {
    var mainField = $("#mainField").children();
    // console.log(mainField,'mainField');
    for(var i = 0; i < mainField.length; i++){
        switch (value) {
            case 'left':
                $("#"+ mainField[i].id).css({ "left": "0px", "float": "none"});
                break;
            case 'right':
                $("#"+ mainField[i].id).css({ "left": "auto", "right": "0px", "float": "right"});
                break;
            case 'bottom':
                $("#"+ mainField[i].id).css({ "top": "auto", "bottom": "0px", "position": "absolute", "float": "none"});
                break;
            case 'top':
                $("#"+ mainField[i].id).css({ "top": "0px", "float": "none"});
                break;
        }

    }
}

//选择所属菜单
function setMenu() {
    mini.open({
        url : bootPATH + "../frame/frame1/pages/formLayout/formDesign_selectMenu.html",
        title : "选择所属菜单",
        width: 500,
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = { action: action, modular: modular, modularId: modularId, parId: parId };
            iframe.contentWindow.SetMenuData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {       //如果点击“确定”
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'----');
                modularId = data.id.replace(/[^0-9]/ig,"");//节点id 去掉字母
                parId = data.pid.replace(/[^0-9]/ig,"");//父节点id
                modular = data.id;//完整的id
                if(parId == '') {
                    parId = 0;
                }
                console.log(modularId,'modularId');
                console.log(parId,'parId');
            }
        }
    })
}

//选择按钮权限
function setButton() {
    mini.open({
        url : bootPATH + "../frame/frame1/pages/formDesign/selectButton.html",
        title : "选择按钮",
        width: 500,
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            var data = { action: action, selected: buttons };
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {       //如果点击“确定”
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                data = mini.clone(data);
                console.log(data,'buttons');
                buttons = data;
            }
        }
    })
}
//根据数据类型设置组件选项
function setCompOption(type) {
    //    文本 文本域 数值 参照 时间 下拉 表格 页签
    if(type.indexOf("varchar")>-1) {//字符串
        cComType.setData([
            {

            },
            {
                'id':'textbox','text':'文本框'
            }, {
                'id':'textarea','text':'文本域'
            },{
                'id':'buttonedit','text':'参照'
            }, {
                'id':'combobox','text':'下拉框'
            }, {
                'id':'fileupload','text':'附件'
            }
        ])
    }else if(type.indexOf("text")>-1) {//超文本
        cComType.setData([
            {

            },
            {
                'id':'textarea','text':'文本域'
            }, {
                'id':'buttonedit','text':'参照'
            }, {
                'id':'combobox','text':'下拉框'
            }
        ])
    }else if(type.indexOf("datetime")>-1) {//时间
        cComType.setData([
            {

            },
            {
                'id':'datepicker','text':'时间选择器'
            }
            // , {
            //     'id':'buttonedit','text':'参照'
            // }, {
            //     'id':'combobox','text':'下拉框'
            // }
        ])
    }else if(type.indexOf("int")>-1) {//整数
        cComType.setData([
            {

            },
            {
                'id':'spinner','text':'数值'
            }
            // , {
            //     'id':'buttonedit','text':'参照'
            // }, {
            //     'id':'combobox','text':'下拉框'
            // },
        ])
    }else if(type.indexOf("numeric")>-1) {//小数
        cComType.setData([
            {

            },
            {
                'id':'spinner','text':'数值'
            }, {
                'id':'buttonedit','text':'参照'
            }
            // , {
            //     'id':'combobox','text':'下拉框'
            // }
        ])
    }
}

//设置默认组件类型
function create_type(type) {
    //    文本 文本域 数值 参照 时间 下拉 表格 页签
    if(type.indexOf("varchar")>-1) {//字符串
        return 'textbox';
    }else if(type.indexOf("text")>-1) {//超文本
        return 'textarea';
    }else if(type.indexOf("datetime")>-1) {//时间
        return 'datepicker';
    }else if(type.indexOf("int")>-1) {//整数
        return 'spinner';
    }else if(type.indexOf("numeric")>-1) {//小数
        return 'spinner';
    }
}

//一键布局
function autoLayout() {
    var layout = mini.get("cLayoutType").getValue();
    var nodes = treeData.getCheckedNodes();
    console.log(nodes);
    if(nodes) {
        for(var i=0;i<nodes.length;i++) {
            if(!nodes[i].isTableName) {//不是表名
                var type = create_type(nodes[i].type);
                var create_main_flag = true;
                if(nodes[i].ptype == "main") {//主表
                    for(var k=0;k<properties.length;k++) {
                        if(properties[k].cTableField == nodes[i].id && properties[k].type != 'table') {
                            create_main_flag = false;
                        }
                    }
                    if(create_main_flag) {
                        create(type,'',{type:'auto'},{
                            name: nodes[i].name, text: nodes[i].text, name_ch: nodes[i].text,
                            cTableFieldType: nodes[i].type,tableName:nodes[i].tableName
                        });
                    }
                }else {//子表
                }
            }
        }
    }
    //生成子表

    var all_nodes = treeData.getData();
    console.log(all_nodes);
    for(var x=0;x<all_nodes.length;x++) {
        if(all_nodes[x].ptype == 'child') {
            var records = [];//生成表格的数据
            var temp = [];
            temp = treeData.getChildNodes(all_nodes[x]);
            for(var y=0;y<temp.length;y++) {
                if(temp[y].checked == true) {
                    records.push(temp[y]);
                }
            }
            if(records.length>0) {
                var first_flag = false;//是否第一次生成
                var created_flag = false;
                var created_field;
                for(var b=0;b<records.length;b++) {
                    for(var k=0;k<properties.length;k++) {
                        if(properties[k].type.indexOf('table')>-1 && records[b].tableName == properties[k].cTableName
                            && records[b].field == properties[k].cTableField) {//已经生成过
                            records[b]['created'] = true;
                            created_flag = true;
                            created_field = records[b].id;
                        }
                    }
                    if(b == records.length-1 && created_flag == false) {//完全第一次生成表格
                        first_flag = true;
                    }
                }
                if(first_flag) {//第一次，生成整表
                    create('table','',{type:'auto'},records);
                }else {
                    //检查数据是否已存在，以及属于哪个表格
                    console.log(records);
                    for(var m=0;m<records.length;m++) {
                        if(!records[m].created) {
                            console.log(records[m]);
                            for(var n=0;n<properties.length;n++) {
                                if(properties[n].type.indexOf('table')>-1 && properties[n].cTableField == created_field) {
                                    console.log(properties[n].c_id);
                                    var c_id = properties[n].c_id.substring(properties[n].c_id.indexOf("_")+1);
                                    addGridCols(c_id,records[m]);
                                }
                            }
                            // addGridCols();
                        }
                    }
                }
                // create('table','',{type:'auto'}, records);
            }
        }
    }

    var mainField = $("#mainField").children();
    console.log(mainField,'mainField');
    var axisTemp = [];
    var mainTemp = [];
    for(var i=0;i<mainField.length; i++){
//         if(mainField[i].className.indexOf('box')>-1 && mainField[i].className.indexOf('grid') == -1) {//主表组件
        if(mainField[i].className.indexOf('box')>-1) {//主子表组件
            axisTemp.push({
                clear: 'both', left: mainField[i].offsetLeft,
                top: mainField[i].offsetTop, position: "absolute",
                "margin-left": '',"margin-bottom": ''
            });
            mainTemp.push(mainField[i]);
        }
    }
    for(var j=0;j<axisTemp.length; j++){

        $('#' + mainTemp[j].id).removeAttr("style");
        if(mainTemp[j].className.indexOf('grid')>-1) {//子表组件

            $('#' + mainTemp[j].id).css(axisTemp[j]);
            $('#' + mainTemp[j].id).css({
//                clear: 'both',
//                left: axisTemp[j].offsetLeft,
//                top: axisTemp[j].offsetTop,
//                position: "absolute",
//            	  "margin-top": 30,
                display: "block"
            });
        }else {
            $('#' + mainTemp[j].id).css(axisTemp[j]);
        }
    }

}

//拖拽组件到主面板事件
function onMenuDrag(type,record) {
    console.log(type);
    mainField.ondragover = function (target) {
        target.preventDefault(); //默认是不接受被拖拽元素的,所以要禁用默认事件
    }
    record.cTableFieldType = record.type;
    mainField.ondrop = function (e) {//面板松开鼠标
        if(record.ptype == 'main') {
            //判断是否被选中，若已被选中则不生成
            var flag = true;
            for(var i=0;i<properties.length;i++) {
                if(record.name == properties[i].cTableField && properties[i].type != 'table') {
                    flag = false;
                }
            }
            if(flag) {
                var coordinates = {x:e.offsetX, y:e.offsetY, type:'drag'};//坐标
                create(type,'',coordinates,record);
                treeData.checkNode(record);
            }
        }else if(record.ptype == 'child') {
            if(record.isTableName) {//子表根节点
                var coordinates = {x:e.offsetX, y:e.offsetY, type:'drag'};//坐标
                var tableData = treeData.getChildNodes(record);
                console.log(tableData);
                var records = [];//生成表格的数据
                for(var t=0;t<tableData.length;t++) {
                    if(tableData[t].checked == true) {
                        records.push(tableData[t]);
                    }
                }
                if(records.length>0) {
                    var first_flag = false;//是否第一次生成
                    var created_flag = false;
                    var created_field;
                    for(var b=0;b<records.length;b++) {
                        for(var k=0;k<properties.length;k++) {
                            if(properties[k].type == 'table' && records[b].name == properties[k].cTableField) {//已经生成过
                                records[b]['created'] = true;
                                created_flag = true;
                                created_field = records[b].id;
                            }
                        }
                        if(b == records.length-1 && created_flag == false) {//完全第一次生成表格
                            first_flag = true;
                        }
                    }
                    if(first_flag) {//第一次，生成整表
                        create('table','',coordinates,records);
                    }else {
                        //检查数据是否已存在，以及属于哪个表格   here
                        console.log(records);
                        for(var m=0;m<records.length;m++) {
                            if(!records[m].created) {
                                console.log(records[m]);
                                for(var n=0;n<properties.length;n++) {
                                    if(properties[n].type == 'table' && properties[n].cTableField == created_field) {
                                        console.log(properties[n].c_id);
                                        var c_id = properties[n].c_id.substring(properties[n].c_id.indexOf("_")+1);
                                        addGridCols(c_id,records[m]);
                                    }
                                }
                                // addGridCols();
                            }
                        }
                    }
                }
            }
        }else if(record.ptype == 'other') {
            var coordinates = {x:e.offsetX, y:e.offsetY, type:'drag'};//坐标
            create(type,'',coordinates,record);
        }
    }
}

function addForm() {
    mini.open({
        url : bootPATH + "../frame/frame1/pages/formDesign/selectDesignMode.html",
        title : "请选择模式",
        width: 300,
        height:230,
        onload: function () {       //弹出页面加载完成
            var iframe = this.getIFrameEl();
            iframe.contentWindow.SetData();
        },
        ondestroy: function (action) {  //弹出页面关闭前
            if (action == "ok") {
                var iframe = this.getIFrameEl();
                var data = iframe.contentWindow.onTableOk();
                designMode = mini.clone(data);
                console.log(designMode,'设计模式');
                if(designMode == 'complex') {
                    $("#cTree").css({
                        display: "inline-block"
                    })
                }else {
                    $("#cTree").css({
                        display: "none"
                    })
                }

                //保存后清空表单
                if(openId = '' || openId == undefined || openId == "") {
                    if(properties.length>0) {//设计了表单且第一次保存
                        save();
                    }
                }else {
                    save();
                }
                openId = '';//设为add下第一次保存
                reloadForm();
                // reloadTab();//刷新
            }
        }
    })
}

//清空表单
function reloadForm() {
    clearForm();//清空右侧栏
    init('enable');
    // treeData.reload();//刷新左侧树形
    $( "#mainField" ).empty();//清空画布
    properties = [];
    click_type = '';
}
//重置按钮
function resetBtnFunc() {
    mini.confirm("确定重置？", "确定？",
        function (action) {
            if (action == "ok") {
                reloadForm();
                mini.showTips({
                    content: "重置成功",
                    state: 'success',
                    x: 'Center',
                    y: 'Center',
                    timeout: 2000
                });
            }
        }
    );
}

// 设置遮罩
function mask() {
    mini
        .mask({
            el : document.getElementById('treeData'),
            html : "<div></div>",
            // cls : "mini-mask-loading",
            style : "height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
        });
    mini
        .mask({
            el : document.getElementById('form1'),
            html : "<div></div>",
            // cls : "mini-mask-loading",
            style : "height: 100%;filter:alpha(Opacity=80);-moz-opacity:0.5;opacity: 0.5;"
        });
}
// 取消遮罩
function unmask() {
    mini.unmask(document.getElementById('treeData'));
    mini.unmask(document.getElementById('form1'));
}

//设计器面板自适应尺寸
function bindResize(el) {
    //初始化参数
    var els = el.style,
        //鼠标的 X 和 Y 轴坐标
        x = y = 0;

    $(el).mousedown(function (e) {
        //按下元素后，计算当前鼠标与对象计算后的坐标
        x = e.clientX - el.offsetWidth, y = e.clientY - el.offsetHeight;
        el.setCapture ? (
            //捕捉焦点
            el.setCapture(),
                //设置事件
                el.onmousemove = function (ev) {
                    mouseMove(ev || event)
                },
                el.onmouseup = mouseUp
        ) : (
            //绑定事件
            $(document).bind("mousemove", mouseMove).bind("mouseup", mouseUp)
        )
        //防止默认事件发生
        e.preventDefault()
    });
    //移动事件
    function mouseMove(e) {
        els.width = e.clientX - x + 'px', //改变宽度
            els.height = e.clientY - y + 'px' //改变高度
    }
    //停止事件
    function mouseUp() {
        el.releaseCapture ? (
            //释放焦点
            el.releaseCapture(),
                //移除事件
                el.onmousemove = el.onmouseup = null
        ) : (
            //卸载事件
            $(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp)
        )
    }
}
/**----------------------------------------公共函数 end--------------------------------------*/
 function modifyfy(){
    addBtn.enable();
    mini.get("setButtonBtn").enable();
    mini.get("setMenuBtn").enable();
    mini.get("saveBtn").enable();
    mini.get("modify").disable();

    var form2 = new mini.Form("#mainField")
    var form = new mini.Form("#form1")
    // var treeData=mini.get("treeData");
    // var rect=mini.get("thisId");
    form.setEnabled(true);
    form2.setEnabled(true);
    treeData.enable();


}

// var cols = CircularJSON.stringify(mini.get(properties[j].c_id).getColumns());
// 鼠标释放的位置是页签的范围之内，获取表格被点击的数据